Search⌘ K
AI Features

Lossy Zip of Iterators

Explore how Python's zip function processes multiple iterators and why some elements can disappear in the zipped output when iterables are unequal in length. Understand the mechanics behind this behavior and learn the proper way to use zip to preserve all intended data. This lesson helps you avoid common mistakes when combining iterators in Python programming.

We'll cover the following...

Zipping up lists will keep them all safe in one place, right? Let’s find out!

Python 3.5
numbers = list(range(7))
print(numbers)
first_three, remaining = numbers[:3], numbers[3:]
print(first_three, remaining)
numbers_iter = iter(numbers)
print(list(zip(numbers_iter, first_three)))
# so far so good, let's zip the remaining
print(list(zip(numbers_iter, remaining)))

Where did element 3 go from the numbers list?

Explanation

...