Rodrigo πŸπŸ“ Profile picture
Aug 25 β€’ 10 tweets β€’ 4 min read
Here are 3 simple ways in which you can reverse a Python 🐍 list.

Let's see how they are different. >>> lst = [42, 73, 0] >>> rev1 = reversed(lst) >>> rev2 = ls
#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: >>> reversed(lst) <list_reverseiterator object at 0x00000241
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] = 9
#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: >>> 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) >>>
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]
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 πŸ™ƒ >>> lst = [42, 73, 0] >>> lst.reverse() >>> lst [0, 73, 42]
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
γ€€

Keep Current with Rodrigo πŸπŸ“

Rodrigo πŸπŸ“ Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @mathsppblog

Aug 26
Here are 3 ways in which you can create a Python 🐍 dictionary.

I bet you never used the last one πŸ€” >>> dict([(1, "one&quo...
#1 an iterable of key, value pairs.

The built-in `dict` can take an iterable with key, value pairs.

Useful, for example, when you have a bunch of keys and a bunch of values that you put together with `zip`: >>> dict([(1, "one&quo...
#2 keyword arguments

You can use the keyword arguments to `dict` to define key, value pairs in your dictionary!

However, this only works if your keys are valid variable names: # Values don't have to be s...
Read 7 tweets
Aug 4
How can you define an immutable object in Python 🐍?

It is not obvious, but it can be done.

Come with me, let's create an immutable `Person` object πŸš€ >>> p = Person("Mickey Mouse", 93) >>> p.name 'Mic
There are two key steps.

The first one is setting `__slots__` to the empty list `[]`.

By setting `__slots__` to the empty list, we make it so that no attributes can be assigned to our class: >>> class C: ...     __slots__ = [] ... >>> c = C()  >>> c.r
Finally, to define the attributes we actually care about and to make those immutable...

We inherit from `tuple`, save the attributes as tuple values, and use properties to fetch them!

Here is what the `Person` implementation looks like πŸ‘‡

Quite cool, right? class Person(tuple):     __slots__ = []     def __new__(cls,
Read 4 tweets
Jul 4
What is `__new__` for?

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 πŸš€ class MyPythonClass:     def __new__(cls, ...):         # Wh
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: >>> x = 3.5 >>> x.__init__(42.73) >>> x 3.5
Notice how I tried to (re-)initialize `x` and nothing happened!

This is different from what happens to, say, a list object: >>> mylist = [73, 42] >>> mylist.__init__((1, 3, 5)) >>> myl
Read 15 tweets
Jul 3
The other day, I waited over 1h for the bus.

Here's what that taught me about logic: Image
It was Sunday, and on Sundays the bus has a reduced schedule.

There is one bus per hour, and they show up approximately at 5min past the hour.

So, at 1:55pm, I walked to the bus stop for the 2:05pm bus, with plenty of breathing in case the bus was running early.
When I got to the stop, two women were sitting there, clearly waiting for the same bus as me.

And we waited.

2:05pm and no bus in sight.

2:15pm and still no bus…

2:25pm and still no bus!
Read 11 tweets
Apr 11
Here is some Python 🐍 code using

- decorators
- callable classes
- custom operators
- β€œfunctional” function composition
- arbitrary args and kwargs

Here is a breakdown of everything that is going on πŸ‘‡
Let us start... from the end!

The assignment to `f` takes 3 functions:

- `add_two`
- `divide_3_floor`
- `s`

and then combines them.

The `|` is in charge of doing this combination, but what combination is this?
The `|` is doing some β€œmagic” I asked it to do, this is not default behaviour in Python.

`f = g | h` means that the function `f` corresponds to calling `h` after calling `g`.

So, `f(x)` actually means `h(g(x))`.
Read 33 tweets
Apr 11
Here is some Python 🐍 code using

- decorators
- callable classes
- custom operators
- β€œfunctional” function composition
- arbitrary args and kwargs

Here is a breakdown of everything that is going on πŸ‘‡
Let us start... from the end!

The assignment to `f` takes 3 functions:

- `add_two`
- `divide_3_floor`
- `s`

and then combines them.

The `|` is in charge of doing this combination, but what combination is this?
The `|` is doing some β€œmagic” I asked it to do, this is not default behaviour in Python.

`f = g | h` means that the function `f` corresponds to calling `h` after calling `g`.

So, `f(x)` actually means `h(g(x))`.
Read 33 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us on Twitter!

:(