banderlog013
banderlog013

Reputation: 2505

Why this examples of `zip()` code have different outputs?

As far, as I am able to understand, we are unpacking 3 identical iterators in both cases, but output is different.
In first case, it, for some reason, similar to list(zip(c[::3], c[1::3], c[2::3])), in second, it behaves like normal zip().

c = [[a, b] for a, b in itertools.product(list(range(3)), list(range(3)))]

# first example
list(zip(*[iter(c)] * 3))
>[([0, 0], [0, 1], [0, 2]), ([1, 0], [1, 1], [1, 2]), ([2, 0], [2, 1], [2, 2])]

# second example
list(zip(*[iter(c), iter(c), iter(c)]))
>[([0, 0], [0, 0], [0, 0]),
 ([0, 1], [0, 1], [0, 1]),
 ([0, 2], [0, 2], [0, 2]),
 ([1, 0], [1, 0], [1, 0]),
 ([1, 1], [1, 1], [1, 1]),
 ([1, 2], [1, 2], [1, 2]),
 ([2, 0], [2, 0], [2, 0]),
 ([2, 1], [2, 1], [2, 1]),
 ([2, 2], [2, 2], [2, 2])]

Upvotes: 1

Views: 58

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46849

your first example is the same as

it = iter(c)
print(list(zip(*[it, it, it])))  # == list(zip(it, it, it))

this is not the same as your second example list(zip(iter(c), iter(c), iter(c)) where you create 3 fresh iterators.

every time next is called on it this has an influence on what happens the next time it is used.

in the second example the 3 iterators run independently.

Upvotes: 3

Related Questions