Rodrigo πŸπŸš€ Profile picture
Take your Python 🐍 skills to the next level πŸš€! Daily drop of Python knowledge https://t.co/vBcyYaK8hl πŸπŸ’§

Aug 25, 2022, 10 tweets

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.

Keep scrolling