Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 809
ichigo Avatar asked Jan 31 '11 15:01

ichigo


1 Answers

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

like image 163
cemper93 Avatar answered Oct 18 '22 05:10

cemper93