A zip object is an iterator that yields tuples containing corresponding items from aligned input iterables. Use zip when separate sequences hold different attributes of the same items. section 5.3.3
Align task details
for task, date, location in zip(tasks, dates, locations): print(f"{task.title}: by {date} at {location}") Tuple unpacking assigns corresponding values together, avoiding manual index management and improving readability. section 5.3.3
Remember these practical behaviors:
- Pass two or more iterables to zip; each yielded tuple contains one item from every input. section 5.3.3
- Expect zip to stop when the shortest iterable is exhausted. section 5.3.3
- Use itertools.zip_longest when iteration should continue through the longest input, filling missing positions with None by default. section 5.3.3
Build dictionaries from paired data
with open("tasks.txt", newline="") as file: csv_reader = csv.reader(file) fields = next(csv_reader) for row in csv_reader: task_dict = dict(zip(fields, row)) print(task_dict) Here, zip pairs each header field with its row value so dict can create a record. section 11.2.2
for task, date, location in zip(tasks, dates, locations):
print(f"{task.title}: by {date} at {location}")
View the focused task-alignment loop using zip and tuple unpacking. section 5.3.3
Listing 11.10 Reading a CSV file with a header using the csv_reader
with open("tasks.txt", newline="") as file:
csv_reader = csv.reader(file)
fields = next(csv_reader) #1
print("Field:", fields)
for row in csv_reader:
task_dict = dict(zip(fields, row)) #2
print(task_dict)
# output the following lines:
Field: ['task_id', 'title', 'urgency']
{'task_id': '1001', 'title': 'Homework', 'urgency': '5'}
{'task_id': '1002', 'title': 'Laundry', 'urgency': '3'}
{'task_id': '1003', 'title': 'Grocery', 'urgency': '4'}
View a complete CSV example pairing header fields with row values. section 11.2.2
