liveBook · Manning

Zip

As explained in Python Workout: 50 ten-minute exercises

zip is a Python built-in function that aggregates corresponding elements from multiple iterables into tuples until the shortest iterable is exhausted.

zip combines corresponding elements from multiple iterables into tuples. Each iteration advances all inputs together and stops when the shortest input ends. section 10.25

Pairing different iterables

>>> list(zip('abc', [10, 20, 30])) [('a', 10), ('b', 20), ('c', 30)] A related exercise asks for myzip([10, 20, 30], 'abc') to return [(10, 'a'), (20, 'b'), (30, 'c')]. section 3.5 section 10.25

Practice the underlying behavior by:

  • Writing a generator function that yields one tuple per index. section 10.25
  • Comparing the built-in iterator with a list-producing implementation for equal-length inputs. section 3.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines indexed tuple production and shortest-input termination, then practices reimplementing the behavior with a generator.
Examples
Uses zip('abc', [10, 20, 30]) and a myzip exercise pairing [10, 20, 30] with 'abc'.
What it assumes
Assumes familiarity with iterables and generator functions while practicing iterator behavior through reimplementation.
What you can do after
Build it from scratch by writing a generator that yields paired tuples until an input is exhausted.
How it connects
Connects iterables, tuples, iterators, generator functions, lists, indexes, and slices.

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 Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.