Reputation: 1
From my understanding, tee
is supposed to make independent copies of an iterator, each of which can be exhausted individually. However, when exhausting the teed copies, sometimes the original iterator is intact, and at other times (e.g., when zip
is involved), it is exhausted instead. Why is this happening? Am I missing some nuance in the semantics of tee
and zip
?
Expected behavior for range(3)
. The original iterator is intact and can be exhausted separately.
a = range(3)
a1,a2 = tee(a,2)
print(list(a1), list(a2), list(a))
>> [0, 1, 2], [0, 1, 2], [0, 1, 2]
Unexpected behavior for zip(range(3),range(3,6))
. The original iterator is exhausted when the copies are exhausted.
a = zip(range(3),range(3,6))
a1,a2 = tee(a,2)
print(list(a1), list(a2), list(a))
>> [(0, 3), (1,4), (2,5) ], [(0, 3), (1, 4), (2,5)], []
Upvotes: -1
Views: 55
Reputation: 1
Following comment by Michael Butcher, range(3)
is an iterable, whereas iter(range(3))
is an iterator, which behaves similar to zip(...)
.
a = iter(range(3))
a1,a2 = tee(a,2)
print(list(a1),list(a2),list(a)
>> [0, 1, 2], [0, 1, 2], []
Upvotes: 0