Python · Some intermediate topics
zip()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — The Problem
Imagine you have two separate lists — Codémon names and their levels — and you want to pair them up. You could use `range(len(...))` but that's clunky.
names = ["Aquachu", "Pyrochu", "Florachu"] levels = [15, 25, 10] for i in range(len(names)): print(names[i], levels[i])
This works, but it's not very Pythonic. Python has a cleaner way: `zip()`! Let's see how it works.
Exercise 2 — Using zip()
`zip()` takes two (or more) lists and pairs their elements together. You get tuples of matching items.
names = ["Aquachu", "Pyrochu", "Florachu"] levels = [15, 25, 10] for name, level in zip(names, levels): print(f"{name}: Level {level}")
Much cleaner! `zip()` pairs `names[0]` with `levels[0]`, `names[1]` with `levels[1]`, etc.
Exercise 3 — What zip() Returns
`zip()` creates pairs (tuples). Let's see what it looks like when converted to a list.
names = ["Aquachu", "Pyrochu", "Florachu"] levels = [15, 25, 10] result = list(zip(names, levels)) print(result) print(type(result[0]))
zip() is Lazy
`zip()` doesn't create all pairs at once. It generates them one by one as you loop. That's why we need `list()` to see all pairs at once.
Exercise 4 — zip() Output
What is printed?
a = ["Aquachu", "Pyrochu"] b = [10, 20] result = list(zip(a, b)) print(result)
Options
• `[("Aquachu", 10), ("Pyrochu", 20)]`
• `["Aquachu", 10, "Pyrochu", 20]`
• `[("Aquachu", "Pyrochu"), (10, 20)]`
• `{"Aquachu": 10, "Pyrochu": 20}`
Hint : `zip()` pairs elements at the ***same index*** into tuples.
Exercise 5 — Complete the zip
Complete the code to pair each Codémon with its element.
names = ["Aquachu", "Pyrochu", "Florachu"] elements = ["Water", "Fire", "Plant"] for name, elem in ____(names, ____): print(f"{name} - {elem}")
Options: zip elements enumerate names range
Hint : Which function pairs elements from two lists? And which list contains the elements?
Exercise 6 — Zipping 3+ Lists
`zip()` works with any number of lists, not just two!
names = ["Aquachu", "Pyrochu", "Florachu"] elements = ["Water", "Fire", "Plant"] levels = [15, 25, 10] for name, elem, lv in zip(names, elements, levels): print(f"{name} ({elem}) - Lv.{lv}")
Exercise 7 — Zip Three Lists
Complete the code to combine names, HP, and levels.
names = ["Aquachu", "Pyrochu"] hps = [100, 120] levels = [15, 25] for name, hp, lv in zip(names, hps, ____): print(f"{name}: ____ HP, Lv.{lv}")
Options: levels hp hps name lv
Hint : The third list goes inside `zip()`. Inside the f-string, use the variable that holds the HP value.
Exercise 8 — zip() with Different Lengths
What if the lists have different lengths? `zip()` stops at the shortest list. No error, just silent truncation.
names = ["Aquachu", "Pyrochu", "Florachu", "Zap"] levels = [15, 25] for name, level in zip(names, levels): print(f"{name}: Level {level}") print(f"Only {len(list(zip(names, levels)))} pairs!")
Keep All Elements?
If you need to keep ALL elements (even from the longer list), use `itertools.zip_longest()` from the `itertools` module. But `zip()` is usually what you want.
Exercise 9 — Different Lengths
What is printed?
a = ["Aquachu", "Pyrochu", "Florachu"] b = [10, 20] print(len(list(zip(a, b))))
Options
• `3`
• `2`
• `5`
• `Error`
Hint : `zip()` stops at the ***shortest*** list. How many elements does `b` have?
Exercise 10 — zip() to Create Dictionaries
A super useful trick: you can pass `zip()` to `dict()` to create a dictionary from two lists!
names = ["Aquachu", "Pyrochu", "Florachu"] levels = [15, 25, 10] team = dict(zip(names, levels)) print(team) print(team["Pyrochu"])
The first list becomes the keys, the second becomes the values. Very handy!
Exercise 11 — Create a Dict with zip
Complete the code to create a dictionary mapping Codémon to their elements.
names = ["Aquachu", "Pyrochu"] elements = ["Water", "Fire"] team = ____(zip(names, ____)) print(team)
Options: dict list elements names tuple
Hint : Which function creates a dictionary from pairs?
Exercise 12 — Codémon Team Builder
You have 3 separate lists. Combine them! 1. Use `zip()` to pair names, elements, and levels together 2. Loop through and print each Codémon as `"#1: Aquachu (Water) - Lv.15"` 3. Create a dictionary mapping names to levels 4. Print the dictionary Hint: use `enumerate()` with `zip()` for the numbering!
Starter code
names = ["Aquachu", "Pyrochu", "Florachu", "Zap"] elements = ["Water", "Fire", "Plant", "Electric"] levels = [15, 25, 10, 30] # 1 & 2: Print numbered roster # 3 & 4: Create and print dict
Back to the course