Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to iterate over a Python list in reverse as fast as possible

I'm using Python 3.2.3. What's the fastest way to iterate over a list in reverse? [::-1], reversed, list.reverse() or maybe some other way? I'm dealing with a list of about 5e6 elements or so, so I really need to avoid copying the list.

like image 860
wenderen Avatar asked Jul 14 '12 19:07

wenderen


2 Answers

>>> from timeit import Timer
>>> t = Timer('[x for x in l[::-1]]', 'l = list(range(100000))')
>>> t.timeit(number=1000)
5.549649953842163
>>> t = Timer('l.reverse(); [x for x in l]', 'l = list(range(100000))')
>>> t.timeit(number=1000)
4.548457145690918
>>> t = Timer('[x for x in reversed(l)]', 'l = list(range(100000))')
>>> t.timeit(number=1000)
4.428632974624634

Conclusion: reversed() is marginally faster than l.reverse() on a list with 100000 items. This of course is even more true if you don't actually loop over the whole list, and it stops being true if you use the list more than once.

l[::-1] is outdated since 2.4 that introduced reversed().

like image 153
Lennart Regebro Avatar answered Oct 22 '22 06:10

Lennart Regebro


reversed should be best as it returns an iterator, so it doesn't copy the list, just yields one element at a time. (list.reverse() also will not copy the list, but it will mutate it, so the list will be backwards after you're done, whereas reversed doesn't modify the original list.)

like image 24
BrenBarn Avatar answered Oct 22 '22 04:10

BrenBarn