Search code examples
pythonloopsxrange

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.


Solution

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