Do you want to master Python 🐍 list comprehensions?

Do you want to become more proficient working with lists in Python 🐍?

If you answered with β€œyes”, then here's a cheatsheet of mine to help you out.

This is also a thread πŸ‘‡πŸ§΅ that breaks it down and explains everything:
First off, here is the anatomy of a list comprehension.

There's 4 parts to a list comp:
1. enclosing brackets to create the list [];
2. expression that transforms your data;
3. `for` iteration over the initial data;
4. (optional!) condition to filter some data.
Do list comprehensions look confusing?

Maybe.

But that's because you didn't realise that list comprehensions have equivalent `for` loops!

The coloured boxes below show the equivalent bits in the list comp and in the `for` loop:
Here is an example list comprehension building a series of square numbers.

Try to work out the equivalent `for` loop and study this example until it makes sense!
Bonus points if you realise the previous list comprehension, using the condition to filter, is equivalent to the better

```py
[n ** 2 for n in range(0, 10, 2)]
```

But that beside the point, here.

Here's some more examples...
Let's take a sentence and split it into words.

Now, let's upper case each of the words.

Then, let's upper case each word, but only if it was all lower case before.

Again, study this example and write out the nested version of this is needed.
Here's one final example, for now.

Again, we break a sentence into words, and then figure out the length of each of the words.

Then, we do the same thing, but only figure out the length of words that do not have any punctuation whatsoever.
List comprehensions are already showing how powerful and useful they can be πŸ”₯!

But list comprehensions can get even more powerful than this!

Did you know you can nest `for` loops?

Useful when you have nested data.
But the nested `for` loops can be independent of one another.

This, in turn, is useful if you need to draw data from multiple iterables to combine them.

This type of situation is also often dealt with by using the built-in function `zip`.
Similarly, you can nest several `if` statements to create more complex filters.

The `if`s to the right only get triggered if the `if`s to the left evaluate to `True`.

This is the same as combining the conditions with an `and`, because of Boolean short-circuiting.
This shows that `for` loops can be nested/chained, and so can `if` statements.

This is, probably, the thing that confuses most people: the order in which things need to be written.

The very first thing in the list comprehension is the final, possibly transformed, value...
Then, from left to right, come all the nested `for` and `if` statements, from top to bottom.

This shows that it is a bad idea to nest too many things in a list comprehension.

That's because it creates a large distance between name usage and name definition.
This thread is coming to an end, but there's still a couple of things I'd like to say.

There's two other Pythonic use cases for list comprehensions.

One of those, is to replace usages of `map`:
The other use-case, a similar one, is to replace usages of `filter`:
⚠ But there's something worth mentioning.

I'm not saying that `map` and `filter` are useless.

There _are_ use cases for those two built-ins.

If you want to learn about those, you can follow @mathsppblog, I'll write about it in the future.
This was a breakdown of the cheatsheet you saw in the beginning, which you can get for free πŸ‘‡

The cheatsheet, in turn, was me summarising my latest blog article, where I introduce list comprehensions: πŸ”— mathspp.com/blog/pydonts/l…

mathspp.gumroad.com/l/cheatsheet_l…
That's it for now!

If you want to level up your Python 🐍 game, and if you are a curious person, follow @mathsppblog for more great content!

Also, if you found value in this thread, retweet it for others to learn something new today πŸ˜ƒ
Here's a TL;DR of this thread:

1. list comps have 4 parts, 1 of which is optional;
2. list comps have equivalent `for` loops that are helpful to understand the list comp;
3. you can nest arbitrarily many `for`s;
4. the nested `for` loops can be independent of each other;
5. you can nest arbitrarily many `if`s;
6. nesting `if`s is equivalent to combining conditions with the `and` operator;
7. all these things can be mixed and nested;
8. nesting too much is a bad idea;
9. `map` and `filter`-like behaviour can be implemented with list comps.

β€’ β€’ β€’

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

25 Sep
What's the BEST way to learn Python 🐍?

I've been writing Python for 10 years and taught 100s of people.

Here is a FAQ with actionable advice πŸ‘‡πŸ§΅

But everyone is different, so share your thoughts as well πŸ‘‡πŸ’¬ to help as many as possible! Image
🐍 β€œHow do I start learning Python?”

Well, I think the answer to this question greatly depends on whether you have (considerable) programming experience with another language or not.

That's because β€œlearning Python” can mean ”learn the syntax of the language”, but...
... it can also mean ”learn how to think like a programmer”.

And, in my opinion, this is something very fundamental that you have to understand!

Being a programmer is also about having that programmer mindset.

Worry not, you can learn it 😊
Read 35 tweets
23 Sep
Do you know what the Python 🐍 `type` is?

But do you _really_ know what it is?

Here is a valuable thread that will give you insights into what `type` is and does.

Let's go πŸ‘‡πŸ§΅
What does `type` do?

You might say that `type` takes an object and returns the type of the argument.

Here are some examples:
Fine, so `type` is a function!

Or is it..?

Take a look at the example above.

`sum` is a built-in function and `type(sum)` returned β€œbuilt-in function or method”.

So, logically, if `type` is a (built-in) function, the type of `type` should give the same thing:
Read 14 tweets
20 Sep
Are you a master of Python 🐍 sequence slicing?

Here is a short thread 🧡 covering four idiomatic slicing patterns that you could get used to.

These four patterns are great because they have a clear interpretation of what they do.

Here we go πŸ‘‡πŸ§΅
🐍 s[n:]

If `n β‰₯ 0`, then `s[n:]` means

πŸ‘‰ β€œSkip the first `n` elements.”

⚠ If `n` is 0, then we skip 0 elements, which is another way of saying we get all of them.
That's the same as `s[:]`.
🐍 s[-n:]

If `n > 0`, then `s[-n:]` means

πŸ‘‰ β€œThe last `n` elements.”

⚠ -0 and 0 are the same, so `s[-0:]` gets all the sequence, like above.
Read 10 tweets
18 Sep
Are you as curious (and nerdy πŸ€“) as I am? πŸ€”

If you are, you are going to love what I'm about to show you 🀯

Let's build a Python 🐍 quine: a program that prints itself!

This thread walks you through the process of building the quine you can see here.

πŸ‘‡πŸ§΅
If we want a program that _prints_ itself, we need to start with a print statement:

```
print()
```

When we run this program, a single newline gets printed as output.

But we want a program that prints itself, right?

So let's try putting the program in the `print`.
For that, we try opening " inside the `print` and we start typing the program, itself, inside the string:

```
print("print()")
```

This outputs

```
print()
```

But now our program grew, so we need to keep up with it inside the string.
Read 11 tweets
17 Sep
πŸ€” Do you ever write some Python 🐍, look at it, and get the feeling there MUST be a better ✨ way to do that..?

I get that ALL the time! πŸ˜…

That's why I started researching and writing articles to help me (and you!) write better code.

Here's all 28 of them (so far!) πŸ‘‡πŸ§΅
I have also been compiling all the articles into an eBook πŸ“–, that I am "selling" for free πŸ’Έ.

Why?

I decided to make it free because that's how I learned Python: from free books and articles, available online.

Here's the link to the free book:

gum.co/pydonts
01 - Pydon't disrespect the Zen of Python

If you type `import this` in a Python REPL, you will be presented with the Zen of Python, a document with some guidelines that you can follow when writing code.

It's not a religion!

Just some guidelines :)

mathspp.com/blog/pydonts/p…
Read 32 tweets
9 Sep
Have you ever had a hard time debugging 🐞 a Python 🐍 script?

If you say you haven't, you're lying! πŸ˜†

Let me show you something that you're gonna love me for!

Run your script with the `-i` flag!

By doing so, you get a REPL when the script finishes, EVEN with errors πŸ’£

1/4
Let me show you an example.

Below is a piece of code I wrote in a script called `foo`.

If you look closely, you'll see I'm generating 100 random integers...

All of them between 0 and... 0! So I'll generate 100 zeroes (my bug).

Later, a 0/0 division will throw an error.

2/4
When I run the code with the `-i` flag, the terminal shows the error and immediately opens a REPL!

From within the REPL I can inspect my variables and figure out what went wrong!

Isn't this amazing ⁉

3/4
Read 5 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

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

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(