Zipping Smart
zip() looks simple… until you really need it. And then it becomes your secret weapon.
In Python, zip() combines multiple iterables element by element, returning an iterator of tuples:
a = [1, 2, 3]
b = ['a', 'b', 'c']
zipped = list(zip(a, b))
print(zipped) # [(1, 'a'), (2, 'b'), (3, 'c')]
This is great for parallel iteration, exporting columns, and dynamic data pairing.
🧩 Intermediate Tricks
1. 🔁 Unzipping with * operator
pairs = [(1, 'x'), (2, 'y'), (3, 'z')]
nums, letters = zip(*pairs)
print(nums) # (1, 2, 3)
print(letters) # ('x', 'y', 'z')
2. ⚠️ Zipping Uneven Lists
Want to zip to the longest list instead?
from itertools import zip_longest
list(zip_longest(a, b, fillvalue='-'))
# [(1, 'a'), (2, 'b'), (None, 'c')]
🛠 Real Use Case: CSV Export with zip()
Let’s say you’re building a log analyzer and you’ve collected 3 lists: timestamps, error types, and messages.
timestamps = ['10:01', '10:05', '10:10']
errors = ['404', '500', '200']
messages = ['Not Found', 'Server Error', 'OK']
rows = zip(timestamps, errors, messages)
with open("log_report.csv", "w") as f:
f.write("time,error,message\n")
for row in rows:
f.write(','.join(row) + '\n')
🧰 Toolkit Function
import os
def export_columns_to_csv(filename, *columns):
with open(filename, 'w') as f:
for row in zip(*columns):
f.write(','.join(map(str, row)) + '\n')
print(f"✅ File saved at: {os.path.abspath(filename)}")
export_columns_to_csv("my.csv", [1, 2], [3, 4], [5, 6])
🎯 Final Thoughts
zip() is not just for toy problems. It’s a core tool for backend scripting and automation:
CSV generation
Parallel data processing
Matrix transformations
Dict reconstruction
🔮 Next Week: enumerate()
How to use it like a loop ninja, not a beginner.