Understanding the Python Zip() Method (Part 1)
Posted by Mark on May 31, 2022 at 06:44 | Last modified: March 28, 2022 17:39As 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:
Unpacking to two variables (xp, yp) does not work:
“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:
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:
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:
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.