Search⌘ K
AI Features

Zip

Explore how to use Python's zip function to iterate over multiple sequences at once by grouping elements into tuples. Understand zip's behavior with sequences of different lengths and discover how to reverse the zipping process using the unpacking operator.

zip function

Another function you may have seen used in a for loop is zip. It provides a way to loop over more than one sequence in the same loop, as shown below.

svg viewer
Python 3.8
first = ('John', 'Anne', 'Mary', 'Peter')
last = ('Brown', 'Smith', 'Jones', 'Cooper')
age = (25, 33, 41, 28)
for f, l, a in zip(first, last, age):
print(f, l, a)

On the first pass through the loop, f, l, and a are set to the first element of first, last, and age respectively. On the second pass, f, l, and a are set to the second element of first, last, and age, and so on. As you might have guessed, zip is producing tuples that are getting unpacked into f, l, and a.

How zip transforms iterables

zip ...