What is faster for loop using enumerate or for loop using xrange in Python?

What is faster, a for loop using enumerate or using xrange?

EDIT: I have tested, and I just see minimal differences.


Enumerate is slightly faster. Tested in Python 3:

>>>import pygame
>>>pygame.init()
>>>clock = pygame.time.Clock()
>>>a = list(range(100000))
>>>def do_with_range():
...    clock.tick()
...    k = 0
...    for i in range(len(a)):
...        k += a[i]
...    print(clock.tick())
>>>def do_with_enumerate():
...    clock.tick()
...    k = 0
...    for i, j in enumerate(a):
...        k += j
...    print(clock.tick())
>>>do_with_range()
23
>>>do_with_enumerate()
21

If a wouldn't be a list, but a generator, it would be significantly faster to use enumerate (74ms using range, 23ms using enumerate).


You can use the timeit module in the standard library to compare both. The timeit.timeit() function used below takes a statement that it runs 1'000'000 times and returns the total time in seconds. In this test enumerate() is slightly slower.

>>> import timeit
>>> timeit.timeit('for i in xrange(100): a[i]', 'a = list(xrange(100))')
7.2920000553131104
>>> timeit.timeit('for i, o in enumerate(a): o', 'a = list(xrange(100))')
10.359999895095825
>>> timeit.timeit('for i in xrange(100): a[i] + 1', 'a = list(xrange(100))')
10.380000114440918
>>> timeit.timeit('for i, o in enumerate(a): o + 1', 'a = list(xrange(100))')
13.514999866485596

Mu.

For loops can use both enumerate and xrange at the same time, though it would be silly. The enumerate function adds an index so you can tell what the index of an item in your iterable is. The xrange function returns an iterable full of numbers. Use it when you want to do something a certain number of times, instead of for each element in an iterable.

Examples:

for idx, element in ['foo', 'bar', 'baz']:
    print idx, element

for idx in xrange(3):
    print idx
链接地址: http://www.djcxy.com/p/4100.html

上一篇: 范围(len(list))或枚举(list)?

下一篇: 循环使用枚举或在Python中使用xrange循环更快?