by masklinn · 4y ago · 0 comments
Depending how the last iteration is handled, zip(a, b) and zip(b, a) with iterators of different sizes can have different behaviours: if a is shorter than b, a naïve implementation would update b in the zip(b, a) case, but not in the zip(a, b) case.
__builtins__.zip chose to consume iterators in the order they are passed as a parameter, and therefor end up with an assymetric consumption.
That's why itertools.tee exists, so that we can chose case by case.
def a():
yield "a1"
def b():
yield "b1"
yield "b2"
x,y = a(),b()
zip(x,y) # => [("a1","b1")]
next(x) # => raise StopIteration
next(y) # => "b2"
x,y = a(),b()
zip(y,x) # => [("b1","a1")]
next(x) # => raise StopIteration
next(y) # => raise StopIteration