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.
>>> 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()
.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With