liveBook · Manning

Zip

As explained in Python How-To

zip is a Python built-in function that returns an iterator of tuples combining corresponding elements from multiple iterables.

Need to combine information stored in separate lists? `zip` is a Python built-in that aligns corresponding items from two or more iterables. It returns an iterator of tuples, with one item from each iterable in each tuple. The tuple items follow the order of the arguments to `zip`. section 5.1.3 section 5.3.3

Display tasks with their dates and locations

```python titles = ["Homework", "Laundry", "Museum"] dates = ["May 5, 2022", "May 9, 2022", "May 11, 2022"] locations = ["School", "Home", "Downtown"] for title, date, location in zip(titles, dates, locations): print(f"{title}: by {date} at {location}") ``` Output: ```text Homework: by May 5, 2022 at School Laundry: by May 9, 2022 at Home Museum: by May 11, 2022 at Downtown ``` Tuple unpacking gives each aligned value a name without repeatedly indexing three lists. section 5.3.3

For paired keys and values, pass the iterator straight to `dict`: `dict(zip([101, 102, 103], ["Laundry", "Homework", "Soccer"]))` produces `{101: "Laundry", 102: "Homework", 103: "Soccer"}`. Put keys first: argument order determines their position in each tuple. section 5.1.3

Choose how to handle unequal lengths:

  • By default, `zip` stops when the shortest iterable is exhausted; remaining items are not paired. section 5.3.3
  • In Python 3.10 or later, use `zip(a, b, strict=True)` when the iterables must have equal lengths. section 5.3.6
  • Use `itertools.zip_longest` when you need rows through the longest iterable; missing positions appear as `None` in the shown example. 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'}

A CSV header and each subsequent row form another useful pair of iterables: `dict(zip(fields, row))` makes a dictionary for each row. For this common task, `csv.DictReader` provides a cleaner direct approach. section 11.2.2

How Python How-To covers it

How deep it goes
Works through tuple order, unpacking, unequal lengths, and alternatives without exploring iterator implementation internals.
Examples
Pairs task IDs with titles, aligns tasks with dates and locations, and maps CSV headers to row values.
What it assumes
Assumes familiarity with lists and for loops while introducing how `zip` aligns iterables and supports tuple unpacking.
What you can do after
Apply it via Python's `zip` to iterate aligned values or build dictionaries, choosing a length-handling approach when needed.
How it connects
Connects iterables, iterators, tuple unpacking, dictionary constructors, CSV readers, and `itertools.zip_longest`.

Also explained in

Compare how 5 books explain zip →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.