11. Zip

zip() is a built-in function that walks several iterables in parallel. Its signature is:

  • *iterables — two or more iterables (lists, strings, tuples…).
  • On each pass it returns one tuple with the next element of each.
  • It stops when the shortest iterable runs out.

Unpack the tuple in the for header:

Coming from JavaScript? There is no built-in zip; it is like walking several arrays in parallel by index. It stops at the shortest iterable, so no undefined values appear.

#01

Pair two lists

Use letters = ["a", "b"] and numbers = [1, 2]. Loop over zip(letters, numbers) and print the letter and the number in one print() call.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Pair names and ages

Use names = ["Ada", "Alan"] and ages = [36, 41]. Loop over zip(names, ages) and print name is age using an f-string.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Zip three lists

Use a = [1, 2], b = [3, 4] and c = [5, 6]. Loop over zip(a, b, c) and print each triple as 1-3-5 using an f-string.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Stop at the shortest list

Zip [1, 2, 3] with ["a", "b"] and print the number and the letter in one print() call. zip() stops at the shortest list, so only two lines appear.

Print exactly:

Create a free account to save your progress and unlock chapter 2.