Analyze the time and space complexity of zip(). Why is it considered a 'lazy' operation in Python 3, and how does this differ from Python 2?

Python interview question for Advanced practice.

Answer

In Python 3, zip() returns an iterator (a zip object). Complexity: Time: $O(1)$ to create the zip object. It does no work upfront. When iterated, each step takes time proportional to the number of iterables being zipped (e.g., if zipping 3 lists, it calls next() 3 times). Space: $O(1)$. It only stores references to the input iterators and the current tuple being yielded. Vs Python 2: Python 2's zip() returned a list of tuples immediately. This consumed $O(n)$ memory and required processing the entire sequence before returning, which was inefficient for large datasets.

Explanation

zip() stops as soon as the shortest input iterable is exhausted.

Related Questions