What if your loop had two lanes?
The problem...
You have two sequences. Names and scores. Questions and answers. Cities and temperatures.
You need to loop through both at the same time — matching item one from the first with item one from the second.
A manual counter works. But there's a cleaner way.
The idea!
zip() pairs up two sequences and lets you loop through both simultaneously. One loop. Two lanes. Items matched by position.
The syntax
for item_a, item_b in zip(sequence_a, sequence_b):
# item_a — current item from sequence_a
# item_b — current item from sequence_b
Your first zip
names = "Bull Horn Red"
scores = "85 92 78"
for name, score in zip(names.split(), scores.split()):
print(f"{name}: {score}")
A quick note — .split() separates a string into a sequence of words. The result is a list — a concept you'll learn properly later. For now, just read the line as: "separate this string into individual words so zip() can pair them up."
# Bull: 85
# Horn: 92
# Red: 78
Python pairs the first item from each sequence, then the second, then the third. One loop — both sequences covered.
Zipping strings
word_a = "Bull"
word_b = "Horn"
for a, b in zip(word_a, word_b):
print(f"{a} — {b}")
# B — H
# u — o
# l — r
# l — n
Character by character. Position by position.
What happens when sequences have different lengths?
word_a = "Bull"
word_b = "Hi"
for a, b in zip(word_a, word_b):
print(f"{a} — {b}")
# B — H
# u — i
zip() stops at the shortest sequence. The extra items are ignored — no error.
Heads up!
zip()pairs items by position — first with first, second with second- Stops at the shortest sequence — extra items are silently ignored
- Unpack both values:
for a, b in zip(seq_a, seq_b) - Variable names are up to you — pick something readable
The mindset shift
Stop thinking: "I need a counter to match items from two sequences."
Start thinking: "If I need to loop through two sequences together — zip() pairs them up."
What you should understand now
zip()lets you loop through two sequences simultaneously- Items are matched by position — first with first, second with second
- Stops at the shortest sequence — no error, extra items ignored
- Unpack both:
for a, b in zip(sequence_a, sequence_b)