Rodrigo πŸπŸš€ Profile picture
Sep 24, 2021 β€’ 19 tweets β€’ 7 min read β€’ Read on X
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

May 9
Hide private information in your Python code.

Suppose you want to print an email...

But you want to create that cool ro*****@mathspp.com effect.

This is pretty easy to achieve in Python!

All you need to do is use an f-string and use the appropriate format specifiers. Diagram showing how you can use f-strings and their format specification to redact private or sensitive information, like email addresses.  The code from the diagram:  def redact_email(email):     user, _, domain = email.partition("@")     return f"{user[:2]:*<{len(user)}}@{domain}"  print(redact_email("rodrigo@mathspp.com")) # ro*****@mathspp.com
πŸ‘‰ the first thing you do is use `str.partition` to grab the email β€œuser” and the domain.

We will redact only the user (but you could also redact the domain with the same process).

The `user[:2]` shows the first two characters.

That's the β€œro”.

But how do you get β€œro*****”?
πŸ‘‰ use an f-string and the width specifier.

You want to create a field as wide as β€œrodrigo”:

r o _ _ _ _ _

The length of this field is `len(user)`, so you use `{len(user)}` INSIDE the format spec.

This creates a field with the correct width.
Read 6 tweets
May 18, 2023
I know `print` is the first Python 🐍 function you learned! πŸš€

And yet, you don't know this about `print` πŸ‘‡ Image
What you know for sure is that `print` will take an object and it will print it on the screen.

That's the basic functionality it provides: Image
Maybe you don't know that `print` can actually print multiple things!

If you pass multiple arguments, they all get printed: Image
Read 11 tweets
May 17, 2023
I'll tell you the story of a person that had the wrong name…

And how to prevent that in Python 🐍 with properties πŸš€.

πŸ‘‡ Image
John Doe was a regular guy and when he was born, he was inserted into the government's database of people.

They created a new `Person` and added John's details: Image
John never liked his name Doe, though.

So Joe decided to change his name to Smith.

And so he did.

He updated his last name, but the government `Person` STILL had the wrong name! Image
Read 10 tweets
May 14, 2023
Opening a file to read/write is a common task in Python 🐍.

Here is how to do it right! πŸš€

πŸ‘‡ Image
Python has a built-in `open` that takes a file path and opens that file.

Then, you have to specify whether you want to open the file to read, write, or append.

But this isn't half of the story! Image
The default behaviour is to open the file to read/write text.

This works well with TXT or CSV files, for instance.

If you need to open a file to read its binary contents, you can add a `"b"` to the mode: Image
Read 6 tweets
May 13, 2023
The Python 🐍 built-in `round` is great. πŸš€

Here are some tips on it. πŸ‘‡ Image
The purpose of `round` is to… round numbers!

It rounds numbers to the closest integer.

These are some simple examples: Image
However, if the number ends in `.5`, what is the closest integer?

In that case, `round` will choose the even number.

This means it may round up or down πŸ€ͺ

(In school, I was taught to round `.5` up… 🀷) Image
Read 6 tweets
May 12, 2023
Error handling in Python 🐍 made simple. πŸš€

πŸ‘‡ Image
The keyword `try` is used before code that might fail.

So, if you know something can raise an error, you can write it inside a `try` statement: Image
Now that the code is inside a `try` statement, you need to tell Python what error you want to handle, and how.

That's when the keyword `except` comes in! Image
Read 7 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!

:(