python / python/cpython

Add clarification to zip's documentation

Open
#122,043 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Documentation

Using zip on iterators of variable length results in a behavior that I believe would benefit from some additional clarification in the documentation. Take the following example:

>>> a = list(range(3))
>>> b = iter(range(100))
>>> list(zip(a, b))
[(0, 0), (1, 1), (2, 2)]
>>> list(zip(a, b))
[(0, 3), (1, 4), (2, 5)]

This is expected behavior as zip simply stops at the end of the shortest iterable, in this case a. When calling zip again a is restarted whilst b carries on from 3.

The unexpected behavior comes about when we swap the arguments putting the longer iterator as the first argument.

>>> a = list(range(3))
>>> b = iter(range(100))
>>> list(zip(b, a))
[(0, 0), (1, 1), (2, 2)]
>>> list(zip(b, a))
[(4, 0), (5, 1), (6, 2)]

Rather than carrying on from 3 like in the previous example we get a 4. I understand this is due to b being consumed during the zip and there is no way to know which iterator will yield a StopIteration first and so this is the intended behavior.

It may be beneficial to highlight this edge case in the documentation and make the recommendation to try and put the shortest iterator first.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the documentation for Python's built-in zip function and review how it describes stopping at the shortest iterable. Clarify that iterators may be consumed before StopIteration is reached and document the shown argument-order edge case, including the recommendation to put the shortest iterator first. Done means the behavior and recommendation are clear in the zip documentation.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
50/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.