Option FanaticOptions, stock, futures, and system trading, backtesting, money management, and much more!

Understanding the Python Zip() Method (Part 2)

Zip() returns an iterator. Last time, I discussed how elements may be unpacked by looping over the iterator. Today I will discuss element unpacking through assignment.

As shown in case [40] below, without the for loop each tuple may be assigned to a variable:

Zip code snippet 6 (5-31-22)

[37] shows that when assigned to one variable, the zip method transfers a zip object. Trying to assign to two or three variables does not work because zip(a, b, c) contains four tuples. As just mentioned, [40] works and if I print yp, m, and n, the other three tuples can be seen:

Zip code snippet 7 (5-31-22)

I got one response that reads:

     > But since you hand your zip iterables that all have 4 elements, your
     > zip iterator will also have 4 elements.

Regardless of the number of variables on the left, on the right I am handing zip three iterables with four elements each.

     > This means if you try to assign it to (xp, yp, m), it will complain
     > that 4 elements can’t fit into 3 variables.

This holds true for three and two variables as shown in [39] and [38], respectively, but not for one variable ([37]). Why?

Maybe it would help to press forward with [37]:

Zip code snippet 8 (6-3-22)

If assigned to one variable, the zip() object still needs to be unpacked (which may also be accomplished with a for loop). If assigned to four variables, each variable receives one 3-element tuple at once.

In figuring this out, I was missing the intermediate step in the [un]packing. 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)

xp, yp, m = zip(a, b, c) tries to unpack that series of four tuples into three variables. This does not fit and a ValueError results.

for xp, yp, m in zip(a, b, c) unpacks one tuple (ax, bx, cx) at a time into xp, yp and m.

Despite my confusion (I’m not alone as a Python beginner), zip() is always working the same. The difference is what gets unpacked: an entire sequence or one iteration of a sequence. zip(a, b, c) always generates a sequence of tuples (ax, bx, cx).

When unpacking in a for loop, one iteration of the sequence—a tuple—gets unpacked:

     xp, yp, m = (ax, bx, cx)

When unpacking outside a for loop, the entire sequence gets unpacked:

     xp, yp, m, n = ((a0, b0, c0), (a1, b1, c1), (a2, b2, c2), (a3, b3, c3))