You need to iterate over the Python list as quickly as possible

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

+7
source share
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: reverse () is slightly faster than l.reverse () in a list with 100,000 elements. This, of course, is even more true if you do not actually overlap the entire list, and ceases to be true if you use the list more than once.

l[::-1] deprecated since 2.4, which introduced reversed() .

+13
source

reversed should be the best as it returns an iterator, so it does not copy the list, it just gives one element at a time. ( list.reverse() will not copy the list either, but it will mutate it, so the list will be back after you finish, whereas reversed will not change the original list.)

+13
source

All Articles