Python Snippet 2: Quick Sequence Reversal
Python lists have a handy method called reverse
, but it's not always what we want. For a start, we can't use it on other sequence types, like tuples and strings, and it also performs an in-place modification of the original sequence.
Using slices we can get around these limitations, reversing any sequence we like before assigning it to a new variable. If we want to use the same variable name, of course we can, since Python allows us to bind names to new objects at will.
friends = ["Rolf", "John", "Mary"]
friends_reversed = friends[::-1]
print(friends_reversed) # ['Mary', 'John', 'Rolf']
greet = "Hello, World!"
print(greet[::-1]) # "!dlroW ,olleH"
This method uses extended slices to step through a sequence backwards, creating a new sequence containing all of the original sequence's elements.
While this is all pretty neat, just because we can do something, it doesn't mean that we should. When working with lists, you're almost always going to want to use the much more readable reverse
method. You can find documentation for it here.
For other sequence types, this slice reversal is very succinct and might be the best option.
If you want to learn more about slices, we have two posts going into a lot more detail on how they work: Part 1, Part 2.