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

ichigo picture ichigo · Jan 31, 2011 · Viewed 16.9k times · Source

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

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

Answer

cemper93 picture cemper93 · Jan 31, 2011

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