Only index needed: enumerate or (x)range?

后端 未结 8 2139
长发绾君心
长发绾君心 2020-11-29 09:46

If I want to use only the index within a loop, should I better use the range/xrange function in combination with len()

a = [1,2,3]         


        
相关标签:
8条回答
  • 2020-11-29 10:49

    Using xrange with len is quite a common use case, so yes, you can use it if you only need to access values by index.

    But if you prefer to use enumerate for some reason, you can use underscore (_), it's just a frequently seen notation that show you won't use the variable in some meaningful way:

    for i, _ in enumerate(a):
        print i
    

    There's also a pitfall that may happen using underscore (_). It's also common to name 'translating' functions as _ in i18n libraries and systems, so beware to use it with gettext or some other library of such kind (thnks to @lazyr).

    0 讨论(0)
  • 2020-11-29 10:50

    I wrote this because I wanted to test it. So it depends if you need the values to work with.

    Code:

    testlist = []
    for i in range(10000):
        testlist.append(i)
    
    def rangelist():
        a = 0
        for i in range(len(testlist)):
            a += i
            a = testlist[i] + 1   # Comment this line for example for testing
    
    def enumlist():
        b = 0
        for i, x in enumerate(testlist):
            b += i
            b = x + 1   # Comment this line for example for testing
    
    import timeit
    t = timeit.Timer(lambda: rangelist())
    print("range(len()):")
    print(t.timeit(number=10000))
    t = timeit.Timer(lambda: enumlist())
    print("enum():")
    print(t.timeit(number=10000))
    

    Now you can run it and will get most likely the result, that enum() is faster. When you comment the source at a = testlist[i] + 1 and b = x + 1 you will see range(len()) is faster.

    For the code above I get:

    range(len()):
    18.766527627612255
    enum():
    15.353173553868345
    

    Now when commenting as stated above I get:

    range(len()):
    8.231641875551514
    enum():
    9.974262515773656
    
    0 讨论(0)
提交回复
热议问题