Python Forum

Full Version: Unpacking zip object
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Thanks Dean!
(Mar-26-2022, 06:30 PM)deanhystad Wrote: [ -> ]What you were missing is the intermediate step int he packing/unpacking.
zip(a, b, c) produces this series:
('1-6-2017', 265, 'd'), ('1-13-2017', -10, ''), ('1-20-2017', 130, 'd'), ('1-27-2017', 330, '')
or
(a0, b0, c0), (a1, b1, c1), (a2, b2, c2), (a3, b3, c3)

When you do xp, yp, m = zip(a, b, c) it tries to unpack that series of 4 into 3 variables. 4 does not fit into 3, so you get an error.

When you do "for xp, yp, m in zip(a, b, c): you are unpacking the tuple (ax, bx, cx) into xp, yp and m.

To better understand, I've tried these cases:

for xp in zip(a,b,c):
    print(xp)
This outputs a tuple.

for xp, yp in zip(a,b,c):
    print(xp)
This outputs ValueError: too many values to unpack (expected 2)

It expected two (for two variables) and it got four, right? Why are two variables "too many values to unpack" when one variable is acceptable?

for xp, yp, m in zip(a,b,c):
    print(xp)
No more tuples: value from a gets assigned to xp, value from b gets assigned to yp, and value from c gets assigned to m.

for xp, yp, m, n in zip(a,b,c):
    print(xp)
ValueError: not enough values to unpack (expected 4, got 3). I see why four were expected (xp, yp, m, n), but... why wouldn't each tuple (a,b,c) be assigned to a variable?

Actually, without the for loop, each tuple gets assigned to a variable:

xp, yp, m, n = zip(a,b,c)
print(xp)
Unlike the for loop where this was "not enough values to unpack," this outputs the first tuple.

So I'm seeing how zip() works in some different contexts but I'm still a bit fuzzy as to why. Sorry to belabor the point.
Quote:
for xp, yp in zip(a,b,c):
    print(xp)
This outputs ValueError: too many values to unpack (expected 2)
It expected two (for two variables) and it got four, right? Why are two variables "too many values to unpack" when one variable is acceptable?
It is trying to unpack 3 values (ax, bx, cx) into xp, yp, ?
Quote:So I'm seeing how zip() works in some different contexts but I'm still a bit fuzzy as to why.
Zip is always working the same. The difference is what is being unpacked; an entire sequence or one iteration of a sequence. zip(a, b, c) always generates a sequence of tuples (ax, bx, cx). When you unpack in a for loop, you are unpacking the tuple, one iteration of the sequence.
xp, yp, m = (ax, bx, cx)
When you unpack outside the for loop you are unpacking the entire sequence.
xp, yp, m, n = ((a0, b0, c0), (a1, b1, c1), (a2, b2, c2), (a3, b3, c3))
This is no different at all than:
for a in (1, 2, 3, 4):
    print(a)
versus
a, b, c, d = (1, 2, 3, 4)
The difference has to do with what you are unpacking, not zip. And what you are unpacking has to do with where you are unpacking.
Pages: 1 2