Here are 3 simple ways in which you can reverse a Python π list.
Let's see how they are different.
#1: the built-in `reversed`:
The built-in `reversed` accepts a sequence and returns an object that knows how to iterate over that sequence IN REVERSE.
Hence, `reversed`.
Notice it doesn't return a list:
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:
#2: slicing with `[::-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:
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:
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:
Slicing is very powerful and useful, and that is why I wrote a whole chapter of my free book βPydon'tsβ on the subject.
The link to the free book is in my Twitter profile and the chapter can also be read online:
mathspp.com/blog/pydonts/iβ¦
#3: the method `.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 turned around π
There you have it, three ways in which you can reverse a Python list.
I hope this was useful and, if it was, follow me @mathsppblog for more daily Python knowledge π
Extra internet points if you retweet this thread for me π
Here is a quick summary:
Reverse a Python list with:
1. the built-in `reversed` that will notice changes to the original list;
2. slicing `[::-1]` that creates a copy of the original list; and
3. the method `.reverse` that reverses a list in place.
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.