Rodrigo 🐍🚀
Rodrigo 🐍🚀

@mathsppblog

8 Tweets 11 reads Apr 14, 2023
Every Python 🐍 programmer should learn about `itertools`.
It's a great module with lots of elegant and efficient tools! 🚀
You'll write better code with these 👇
The first thing I want to show you is `itertools.⁣zip_longest`.
It's the counterpart to the built-in `zip`.
The built-in will stop at the shortest sequence.
`zip_longest` will go to the end of the longest sequence.
Now, I'll show you what `itertools.repeat` does!
You'll love it! 🐍🚀
You'll love it! 🐍🚀
You'll love it! 🐍🚀
Say goodbye to multiplying lists with a single element!
Another great tool, similar to `repeat`, is `itertools.cycle`.
It comes in handy when you want to repeat a series of values in a cycle.
It's infinite, so be sure to stop it somehow!
I use it a lot with `zip`:
Another thing I really enjoy using is `itertools.pairwise`.
It's the elegant and efficient way of doing `zip(my_list[1:], my_list[:-1])`.
It takes an iterable and gives you pairs of consecutive elements.
Sadly, it's Python 3.10+ only 😢
Finally, let me tell you about `itertools.chain`.
This will let you chain together iterables (lists, strings, tuples, generators, etc.)
This is often more efficient than concatenating lists together, for example.
Useful to put together data from different sources.
✨ And here's a little bonus for you.
Actually, it's only half a bonus…
But `chain` also has `chain.from_iterable`.
It also does chaining, but it chains things that are already inside something like a list.
It kind of “flattens” things out one level.
That's it for now!
If you enjoyed this thread:
👉 follow me @mathsppblog for more Python 🐍 knowledge; and
👉 retweet the tweet below to share this thread with your audience! 🚀
What other `itertools` goodies do you use? Add them here 👇

Loading suggestions...