Have you ever seen anything like this in Python π loops??
I just saw this being used for the first time, ever, and I decided to figure out what the heck this was...
And so here goes the explanation ππ§΅
1/
Foreword:
Python has many amazing capabilities to deal with `for` loops, among which you can count the `zip` and `enumerate` built-ins.
This little thread assumes you are familiar with both.
Read these if you need:
πΒ mathspp.com/blog/pydonts/eβ¦
πΒ mathspp.com/blog/pydonts/zβ¦
2/
When using `zip` and `enumerate` in your `for` loops, something you do often is to unpack the values you are iterating over.
Unpacking, in and out of itself, is an amazing feature of Python, and you can read about it in the linked article if needed.
mathspp.com/blog/pydonts/dβ¦
3/
In short, it allows you to give names to the several variables that you need to access, extracting them from the structure they are in.
E.g.:
4/
So, what sort of thing can you use on the left of the `=` sign?
Naturally, you can use variable names, like in the example above...
But you can actually use anything that can be assigned to!
For example, specific list indices are assignable:
5/
But why stop here?
Dictionary keys can also be assigned to; that's the essence of dictionaries:
6/
Now we can understand how `{}[()]` works.
Can you see it already?
`{}` is an empty dictionary;
`[...]` accesses the dictionary with some key, and
`()` creates an empty tuple, which is a possible dictionary key.
If we replace `{}` with `d`, we can see what's happening:
7/
HOWEVER, if we use `{}` instead of `d`, then we create an βanonymousβ dictionary that is lost as soon as we get out of the loop β after all, the dictionary has no name.
Just that.
Some smoke and mirrors, looks cool, but no black magic π
Here's another silly alternative:
8/
Thank you, @DahlitzF , for igniting the spark that made me write this thread! (cc @python_engineer)
If you liked this thread, consider following me (@mathsppblog) for more content like this; I produce daily content to empower YOU with Python π!
See you around?
P.S. the code above, using `{}[()]`, is NOT good Python code.
It's an interesting party trick, but please do not write it in a serious environment.
Instead, prefer `_` for variables that you intend to ignore, as I explain here:
mathspp.com/blog/pydonts/uβ¦
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.