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

Understanding the Python Zip() Method (Part 1)

As promised at the end of my last post, I’ve done some digging with some extremely helpful people at Python.org. Today I will work to wrap up loose ends mainly by discussing the Python zip() method.

My first burning question (Part 8) asks why L42 plots a line whereas L45 plots a point. The best answer I received says that matplotlib draws lines between points. If you give it X points then it will draw (X – 1) lines connecting those points. I was pretty much correct in realizing L45 receives one point at a time and therefore draws (1 – 1) = 0 lines.

To understand how L45 gets points, I need to better comprehend the zip() method. Zip() returns an iterator. Elements may then be unpacked via looping or through assignment.

Let’s look at the following examples to study the looping approach.

Unpacking to one variable (xp) outputs a tuple with each loop:

Zip code snippet 1 (5-31-22)

Unpacking to two variables (xp, yp) does not work:

Zip code snippet 2 (5-31-22)

“Too many values to unpack” is confusing to me. If there are too many values to unpack for two variables, then why are there not too many to unpack for one? Perhaps the first example should be conceptualized as one sequence with four tuples. If so, then can’t this be conceptualized as one sequence with two tuples unpacked through two loops each?

Looping over the iterator with three variables yields this:

Zip code snippet 3 (5-31-22)

To better illustrate how the value from a gets assigned to xp, the value from b gets assigned to yp, and the value from c gets assigned to m, here is the same example with all variables printed:

Zip code snippet 4 (5-31-22)

Unlike the top example, these are not tuples as no parentheses appear. Each line is just three values with spaces in between.

Looping over the iterator with four variables does not work:

Zip code snippet 5 (5-31-22)

I understand why four were expected (xp, yp, m, n) and as shown in the previous example, only three lists are available to be unpacked up to a maximum of four times.

Next time, I will continue with examples of element unpacking through assignment.

No comments posted.

Leave a Reply

Your email address will not be published. Required fields are marked *