This short article teaches you 3 ways of reversing a Python list.
Here are 3 simple ways in which you can reverse a Python ๐ list:
>>> lst = [42, 73, 0]
>>> rev1 = reversed(lst)
>>> rev2 = lst[::-1]
>>> lst.reverse()
Let's see how they are different.
reversed
The built-in reversed
accepts a sequence and returns an object that knows how to iterate over that sequence in reverse order.
Hence, reversed
.
Notice it doesn't return a list:
>>> reversed(lst)
<list_reverseiterator object at 0x00000241D77BD520>
The list_reverseiterator
object that is returned is โlinkedโ to the original list...
So, if you change the original list, the reverse iterator will notice:
>>> lst = [42, 73, 0]
>>> rev = reversed(lst)
>>> lst[1] = 999999 # Change something in the original list.
>>> for n in rev: # Go over the reverse iterator.
... print(n)
...
0
999999 # This was changed as well.
42
[::-1]
The slicing syntax with brackets []
and colons :
accepts a โstepโ that can be negative.
If the โstartโ and โstopโ are omitted and the โstepโ is -1, we get a copy in the reverse order:
>>> lst = [42, 73, 0]
>>> lst[::-1]
[0, 73, 42]
Slices in Python ๐ are regular objects, so you can also name them. Thus, you could go as far as creating a named slice to reverse lists, and then use it:
>>> lst
[42, 73, 0]
>>> reverse = slice(None, None, -1)
>>> lst[reverse]
[0, 73, 42]
Notice that slices are not โlinkedโ to the original list. That's because slicing creates a copy of the list. So, if you change the elements in a given index, the reversed list will not notice:
>>> lst = [42, 73, 0] # Original list.
>>> rev = lst[::-1] # Reverse copy.
>>> lst[1] = 999999 # Change something in the original.
>>> rev # The copy didn't notice.
[0, 73, 42]
Slicing is very powerful and useful, and that is why I wrote a whole chapter of my free book โPydon'tsโ on the subject.
.reverse
Lists have a method .reverse
that reverses the list in place.
What this means is that you do not get a return value with the reversed list...
Instead, the list itself gets flipped around ๐
>>> lst = [42, 73, 0]
>>> lst.reverse()
>>> lst
[0, 73, 42]
Here is a quick summary:
Reverse a Python list with:
reversed
that will notice changes to the original list;[::-1]
that creates a copy of the original list; and.reverse
that reverses a list in place.This article was generated automatically from this thread I published on Twitter @mathsppblog. Then it was edited lightly.
I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza ๐. Your contribution boosts my confidence and helps me produce this content for you.