Rodrigo ๐Ÿ๐Ÿš€
Rodrigo ๐Ÿ๐Ÿš€

@mathsppblog

16 Tweets 1 reads May 11, 2023
Have you mastered Python's ๐Ÿย `zip` built-in?
It is one of the many powerful tools that Python provides us with to supercharge our `for` loops! ๐Ÿš€
Let me teach you all about it ๐Ÿ‘‡
If I could only tell you one thing about `zip` is that it's useful when you need to put two sequences together.
Or even three.
Or more!
But usually, you'll use it with just two.
Something that might bite you sooner or later is that `zip` doesn't produce a list out of the box, that's why we explicitly call `list` above.
Be mindful of that.
If you REALLY need a list, do the conversion.
More often than not, you won't need the list ๐Ÿ˜‰
In fact `zip` is what's called a (lazy) iterator: it only generates the values as needed.
That's fine, just bear in mind that once you go through the `zip` object, it becomes โ€œemptyโ€!
You can only consume a `zip` object once.
An interesting thing to take note of is what happens when the sequences do not have the same length.
When that's the case, `zip` stops at the end of the shortest sequence.
Sometimes, different lengths are OK.
MOST times, if the sequences have different lengths, that's a bug!
To catch those, use the `strict` keyword argument.
(Python 3.10+ only ๐Ÿ˜ข)
However, sometimes the sequences have different lengths and that's ok.
If you want to exhaust ALL sequences, instead of stopping at the shortest, you can use `itertoolsโฃ.zip_longest`.
By default, it fills empty values with `None`:
If you want to change the default value, use the keyword argument `fillvalue`:
Here's a quick tangent.
If you need to go over a sequence of values over and over again, you can use `itertools.cycle`.
(`cycle` creates an infinite sequence, so DON'T call `list` on thatโ€ฆ)
Now that you've been introduced to `cycle`, you should know that `cycle` and `zip` go nicely together!
`zip` can also be used to intercalate two sequences together.
For that effect, you use `zip` and then you want to flatten out the result.
There's two ways to do that.
The first one uses the โ€œsum trickโ€:
โธ๏ธย Just a quick tangent, here.
This โ€œtrickโ€ isn't really a trick.
`sum` is an algorithm of the family of reductions, so if you know how reductions work, you know why `sum(z, ())` works.
You can read about reductions here:
mathspp.com
โ–ถ๏ธย Back to flattening zipped sequences!
You can also use `itertools.chain`, which will probably infuriate fewer people!
Is it a better approach? ๐Ÿคท
Another cool thing about `zip` is that it can undo itself!
If you have sequences that are zipped together (because you did it or because, you know, reasons!), you can separate them again byโ€ฆ zipping them again!
That's it!
Did I miss anything?
If you enjoyed this thread:
๐Ÿ‘‰ย follow me @mathsppblog for more Python ๐Ÿย knowledge; and
๐Ÿ‘‰ย retweet the tweet below to share this thread with your audience! ๐Ÿš€

Loading suggestions...