Python Forum

Full Version: Parallel iteration with for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm really struggling in understanding how parallel iteration works with for loops.

Here is just some experimental code:

myList = list(zip(['a', 'b', 'c'],['abc', 'def', 'ghi'],[1, 2, 3]))
print(myList)

for i in myList:
    print(i)

for i,j,k in myList:
    print(i,j,k)

for i,j,k in myList:
    print(i,j)

for i,j in myList:
    print(i,j,k)
Output:
[('a', 'abc', 1), ('b', 'def', 2), ('c', 'ghi', 3)] ('a', 'abc', 1) ('b', 'def', 2) ('c', 'ghi', 3) a abc 1 b def 2 c ghi 3 a abc b def c ghi ValueError: too many values to unpack (expected 2)
I understand the first print statement and the first for loop.

The for loops with the i,j,k and i,j is where my understanding breaks down...

It's clearly iterating 3 times because it's printing 3 times..

My tired neurons can't figure out what's happening this late. Someone explain please Heart
(Jul-19-2019, 11:28 PM)Josh_Python890 Wrote: [ -> ]The for loops with the i,j,k and i,j is where my understanding breaks down...

It's clearly iterating 3 times because it's printing 3 times..
Its iterating 3 times because there are 3 tuples in the myList

This is failing
for i,j in myList:
because i and j are not enough for it to unpack. You need 3 for each, or one for the whole tuple, but not 2. You can print 2 as you have to your second to last for loop, but you must loop it with 3. Each element of the iterable is a tuple, then you can specify three variables and each element in the loop will be unpacked to the three.

Another way to view it would be
for first, second, third in [('a', 'abc', 1), ('b', 'def', 2), ('c', 'ghi', 3)]:
Where first is the chars, second is the strings, and third is the ints. If you omit second and third, then first would be the entire tuple. IF you only omit third, then you get a ValueError because its trying to unpack 3 into 2. Whereas if you have 4 in this case, you would get instead
Error:
ValueError: not enough values to unpack (expected 4, got 3)
Google tuple unpacking