Rodrigo πŸπŸš€ Profile picture
Oct 2, 2021 β€’ 16 tweets β€’ 5 min read β€’ Read on X
I love the `enumerate` Python 🐍 built-in!

I love it because your `for` loops become much more readable ✨ if you know how to use it.

Here's a thread πŸ‘‡πŸ§΅ on how `enumerate` will make your Python code so much better.

Let's go πŸš€
Python's `for` loops are amazing!

And yet, many people write too much stuff in their loops.

For example, if you just need to go through a list, you shouldn't be writing this πŸ‘‡
In Python, you can just β€œgo through lists”, you don't need to compute the range of the length of the list!

Instead of the above, you can just write this πŸ‘‡

This is better because you can read it as β€œfor each colour in the list `l`”.
Sometimes, you need to go through an iterable and need the data AND the index.

How do you do that?

That's exactly what `enumerate` is for.

So, whenever you see this pattern πŸ‘‡

That's when you should use `enumerate`.

I'll show an example:
For example, imagine you want to group equal letters of a word with their positions.

How'd you do it?

Think for a second ⏳
If I didn't know about `enumerate`, I would find all the legal indices into a string, and then access the characters β€œby hand”, like so πŸ‘‡

But with `enumerate` I can clean up the code a bit...
Here is a possible implementation (not the best one!) that makes use of `enumerate` πŸ‘‡

Notice how the `for` loop looks like:

```
for idx, letter in enumerate(word):
```

`enumerate` lets us access the indices and the corresponding letters at the same time!

How'd you read this?
I'd read that line as

β€œFor each index and corresponding letter in the enumeration of `word` ...”.

One thing I like about `enumerate` is that it allows me to give a DECENT name to the piece of data I'm working with.

In the example above, I used `letter` to refer to the letters.
Now, what's VERY important to note here is that `enumerate` is not a magical thing that does black magic πŸŒŒπŸ§™β€β™€οΈ

`enumerate` just takes something that you can β€œgo through”

(which is my informal way of referring to iterables)

and then produces pairs of indices and elements πŸ‘‡

⁉
Wait, that doesn't look helpful πŸ˜†

That's because `enumerate` objects are lazy. They only give you the pairs when you need them.

Or ask for them!

Let's ask for them, then...
If we enclose the `enumerate` with a `list`, we'll get all the pairs for inspection πŸ‘‡

Doesn't look that weird, right?

Just some tuples.

What else is there to `enumerate`..?
`enumerate` accepts a cool optional argument called `start`!

With it, you can change the... start of the counting!

What's this useful for..?
Anytime the indices don't match up with a more β€œnatural” counting!

For example, if you need to traverse lines of a file, you'll want to start counting at 1.

Or, e.g., if you truncated the data and now are picking up a later chunk that is not the beginning (index 0)...
We've already covered a lot of ground about `enumerate`, good job πŸ”₯

Let's call it a thread for now 😊

If you want to learn more about `enumerate` and see more code examples, you can check an article I have right here πŸ‘‡πŸ‘‰ mathspp.com/blog/pydonts/e…
If you want to keep learning more about Python 🐍 and improving the quality of your code...

You should definitely follow @mathsppblog, I post quality content, just for you πŸ˜‰

Also, can I ask you something? If you learn from this, retweet the thread πŸ™

🎁 Bonus:

Take a look at the code from before that implemented `group_letters`.

Can you use `defaultdict` to make it cleaner?

See you around πŸ‘‹

β€’ β€’ β€’

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!

:(