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.
β’ β’ β’
Missing some Tweet in this thread? You can try to
force a refresh
The Python π docs say "__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation."...
What does that mean?!
Let me explain π
The first thing I want to show you is that `__init__`, the method that **initialises class instances**, does nothing for immutable objects.
In other words, I'll show that for immutable types, `__init__` is a no-op.
Just take a look at the REPL session below:
Notice how I tried to (re-)initialize `x` and nothing happened!
This is different from what happens to, say, a list object: