Python Zip
Example 1
Basic Example
fb_jersey_numbers = [14, 60, 16]
quarterbacks = ['Y.A. Tittle', 'Otto Graham', 'George Blanda']
zipped = zip(fb_jersey_numbers, quarterbacks)
print(list(zipped))
[(14, ‘Y.A. Tittle’), (60, ‘Otto Graham’), (16, ‘George Blanda’)]
Example 2
Length Mismatch
If the iterables have different lengths, zip() will stop creating tuples when the shortest iterable is exhausted
basseball_jersey_numbers = [44, 32, 24]
players = ['Hank Aaron', 'Sandy Koufax', 'Willie Mays', 'Al Kaline',]
zipped = zip(basseball_jersey_numbers, players)
print(list(zipped))
[(44, ‘Hank Aaron’), (32, ‘Sandy Koufax’), (24, ‘Willie Mays’)]
Example 3
Mismatch no Value
from itertools import zip_longest
zipped_short = zip_longest(basseball_jersey_numbers, players, fillvalue=None)
print(list(zipped_short))
[(44, ‘Hank Aaron’), (32, ‘Sandy Koufax’), (24, ‘Willie Mays’), (None, ‘Al Kaline’)]
Example 4
3 iterables
pitchers = ['Tom Seaver', 'Nolan Ryan', 'Phil Niekro']
teams = ['New York Mets', 'California Angels', 'Atlanta Braves']
strikeouts = [243, 186, 195]
zipped = zip(pitchers, teams, strikeouts)
print(list(zipped))
[(‘Tom Seaver’, ‘New York Mets’, 243), (‘Nolan Ryan’, ‘California Angels’, 186), (‘Phil Niekro’, ‘Atlanta Braves’, 195)]
Example 5
For Loop
points = [30, 24, 35]
assists = [8, 12, 10]
total_contribution = []
for pts, ast in zip(points, assists): total_contribution.append(pts + ast)
print(total_contribution)
[38, 36, 45]
Example 6
Element Wise min or max
seaver_strikeouts = [251, 201, 243]
ryan_strikeouts = [383, 367, 186]
min_strikeouts = [min(seaver, ryan) for seaver, ryan in zip(seaver_strikeouts, ryan_strikeouts)]
print(min_strikeouts)
[251, 201, 186]
Example 7
keys = ['name', 'wickets', 'number']
values = ['Shane Warne', 708, 23]
warne_dict = dict(zip(keys, values))
print(warne_dict)
{‘name’: ‘Shane Warne’, ‘wickets’: 708, ‘number’: 23}
Example 8
numbers = [10, 18, 23]
players = ['Sachin Tendulkar', 'Virat Kohli', 'Shane Warne']
interleaved = [item for pair in zip(numbers, players) for item in pair]
print(interleaved)
[10, ‘Sachin Tendulkar’, 18, ‘Virat Kohli’, 23, ‘Shane Warne’]
Example 9
Modify elements
names = ['Bob Lemon', 'Mickey McDermott', 'Earl Wilson']
strikeouts = [162, 155, 149]
for name, strikeout in zip(names, [k + 10 for k in strikeouts]): print(f"{name} now has {strikeout} strikeouts")
Bob Lemon now has 172 strikeouts
Mickey McDermott now has 165 strikeouts
Earl Wilson now has 159 strikeouts
Example 10
Unzip
zipped = [('Aaron Judge', 52), ('Giancarlo Stanton', 59), ('Joey Votto', 36)]
players, home_runs = zip(*zipped)
print(players)
(‘Aaron Judge’, ‘Giancarlo Stanton’, ‘Joey Votto’)
print(home_runs)
(52, 59, 36)