0

I noticed a straight behaviour when I loop over multiple iterators in Python

>>> from itertools import tee
>>> X,Y = tee(range(3))
>>> [(x,y) for x in X for y in Y]
[(0, 0), (0, 1), (0, 2)]

I expected it to behave identical as

>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

What am I missing? I thought tee as supposed to return independent iterators..

1 Answers1

1

You exhausted the Y iterator, so zip() stopped iterating. Iterators cannot be used repeatedly, once you iterated to the end, that is it. You'd have to produce a new generator for each inner loop.

For your usecase, you'd actually use itertools.product() here, with a repeat parameter:

>>> from itertools import product
>>> list(product(range(3), repeat=2))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343