Using Python zip, zip_longest and the strict flag to stop zip from truncating iterables

Опубликовано: 16 Октябрь 2024
на канале: Pybites
87
3

Today we look at the zip built-in function, which lets you iterate over several iterables in parallel, producing tuples with an item from each one.

Docs: https://docs.python.org/3/library/fun...

We look at its default behavior of stopping when the shortest iterable is exhausted.

We show how you can prevent that by using zip_longest from the itertools module.

You will also learn how "lazy" objects can only be iterated once and how you can cast to a list() to loop through them multiple times.

Lastly we look at zip's new (starting Python 3.10) "strict" flag with which you can force a ValueError to be raised when looping over non equal length sequences (it will hit when the shortest iterable is exhausted).

We hope this is helpful and for an overview of the important built-in functions, check out our overview video:    • Useful Python Built-in Functions [Beg...  

---
We appreciate any feedback 💡 - please use this form so we can always make our content better:
https://form.jotform.com/230941798741062 🙏