5
votes

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

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

3
They are not really interchangeable. What are you trying to do? Can you paste a code sample?Adam Matan
Wow, downvote heaven over here. Let's wait a little for an improved question. Perhaps the poster needs an answer as to why this question is difficult to answer... Let's be a little more welcoming to this new user and help him along on his first post.Benjamin
@Adam: They are if you want to have an index variable handy while you iterate.Marcelo Cantos
@Jochen: High-octane gas will make some cars go faster, and using the right mixture is likely to be much cheaper that buying a different car. As for the question, I think it's perfectly reasonable to ask which is faster. Sometimes little things like this can make a big difference to performance-critical sections of code. In JavaScript, for instance, choosing the right looping construct can make a huge difference.Marcelo Cantos

3 Answers

7
votes

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).

6
votes

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
0
votes

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