liveBook · Manning

Zip

As explained in The Quick Python Book, Fourth Edition

zip is a Python built-in function that aggregates corresponding elements from two or more iterables into tuples, stopping when the shortest iterable is exhausted.

zip combines corresponding elements from two or more iterables into tuples, stopping when the shortest iterable ends. It is useful when parallel data must be processed together. section 8.8

x = [1, 2, 3, 4]
y = ['a', 'b', 'c']                                   #1
z = zip(x, y)
list(z)
 
[(1, 'a'), (2, 'b'), (3, 'c')]                        #2
#1 y is three elements; x is four elements.
#2 z has only three elements.

With x containing four values and y containing three, list(zip(x, y)) produces three pairs: (1, 'a'), (2, 'b'), and (3, 'c'). section 8.8

Use zip when:

  • Parallel lists need to be treated as paired records. section 8.8
  • An iterator is suitable for streaming rows into a writer rather than building a list first. section 22.5.2
  • You need to remember that converting the result with list() materializes the pairs for inspection. section 22.5.2

Writing paired weather data

Extract parallel time and temperature lists, then write paired rows with for time, temperature in zip(time_data, temperature_data): writer.writerow([time, temperature]). The same iterator can be passed directly to writerows().

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines tuple aggregation and shortest-input termination, then demonstrates iterator conversion and CSV consumption.
Examples
Uses unequal lists and paired weather dates and temperatures written to a CSV file.
What it assumes
Assumes familiarity with Python iterables, loops, lists, iterators, and basic file or CSV operations.
What you can do after
Apply zip() to pair parallel data and pass its iterator to a CSV writer or convert it with list().
How it connects
Connects iterable processing with loops, list(), iterators, JSON data, and CSV writers.

Also explained in

Compare how 5 books explain zip →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.