Best way to create a "reversed" list in Python? Best way to create a "reversed" list in Python? python python

Best way to create a "reversed" list in Python?


newlist = oldlist[::-1]

The [::-1] slicing (which my wife Anna likes to call "the Martian smiley";-) means: slice the whole sequence, with a step of -1, i.e., in reverse. It works for all sequences.

Note that this (and the alternatives you mentioned) is equivalent to a "shallow copy", i.e.: if the items are mutable and you call mutators on them, the mutations in the items held in the original list are also in the items in the reversed list, and vice versa. If you need to avoid that, a copy.deepcopy (while always a potentially costly operation), followed in this case by a .reverse, is the only good option.


Now let's timeit. Hint: Alex's [::-1] is fastest :)

$ p -m timeit "ol = [1, 2, 3]; nl = list(reversed(ol))"100000 loops, best of 3: 2.34 usec per loop$ p -m timeit "ol = [1, 2, 3]; nl = list(ol); nl.reverse();"1000000 loops, best of 3: 0.686 usec per loop$ p -m timeit "ol = [1, 2, 3]; nl = ol[::-1];"1000000 loops, best of 3: 0.569 usec per loop$ p -m timeit "ol = [1, 2, 3]; nl = [i for i in reversed(ol)];"1000000 loops, best of 3: 1.48 usec per loop$ p -m timeit "ol = [1, 2, 3]*1000; nl = list(reversed(ol))"10000 loops, best of 3: 44.7 usec per loop$ p -m timeit "ol = [1, 2, 3]*1000; nl = list(ol); nl.reverse();"10000 loops, best of 3: 27.2 usec per loop$ p -m timeit "ol = [1, 2, 3]*1000; nl = ol[::-1];"10000 loops, best of 3: 24.3 usec per loop$ p -m timeit "ol = [1, 2, 3]*1000; nl = [i for i in reversed(ol)];"10000 loops, best of 3: 155 usec per loop

Update: Added list comp method suggested by inspectorG4dget. I'll let the results speak for themselves.


Adjustments

It's worth providing a baseline benchmark/adjustment for the timeit calculations by sdolan which show the performance of 'reversed' without the often unnecessary list() conversion. This list() operation adds an additional 26 usecs to the runtime and is only needed in the event an iterator is unacceptable.

Results:

reversed(lst) -- 11.2 usecslist(reversed(lst)) -- 37.1 usecslst[::-1] -- 23.6 usecs

Calculations:

# I ran this set of 100000 and came up with 11.2, twice:python -m timeit "ol = [1, 2, 3]*1000; nl = reversed(ol)"100000 loops, best of 3: 11.2 usec per loop# This shows the overhead of list()python -m timeit "ol = [1, 2, 3]*1000; nl = list(reversed(ol))"10000 loops, best of 3: 37.1 usec per loop# This is the result for reverse via -1 step slicespython -m timeit "ol = [1, 2, 3]*1000;nl = ol[::-1]"10000 loops, best of 3: 23.6 usec per loop

Conclusions:

The conclusion of these tests is reversed() is faster than the slice [::-1] by 12.4 usecs