So, I start out with this code:
x = [1, [2, 3]]
y = [4, [5, 6]]
z = [7, [8, 9]]
amazing_list = [x, y, z]
and i do a simple list comprehension on it
print [l for l in amazing_list]
prints [[1, [2, 3]], [4, [5, 6]], [7, [8, 9]]] as expected
print [l for i, l in amazing_list]
prints [[2, 3], [5, 6], [8, 9]] as expected
print [a for i, l in amazing_list for a in l]
prints [2, 3, 5, 6, 8, 9] as expected,
but then here's the kicker, here's where something isn't expected: what I'm trying to accomplish with the next line of code that I'm about to present is I'm just trying to print 2, 5, 8 (the first element of the list inside of the list):
print [a for i, l in amazing_list for a, b in l]
but this prints TypeError: 'int' object is not iterable. Why?
I know that these accomplish what I want to accomplish:
print [l[0] for i, l in amazing_list]
print [a for a, b in [l for i, l in amazing_list]]
But what I want to find is why, conceptually, my first attempt at the comprehension didn't work.
You're getting a little carried away with the unpacking.
Note that the comprehension you're trying to understand
[a for i, l in amazing_list for a, b in l]
is logically equivalent to the following:
tmp = []
for i, l in amazing_list:
for a, b in l:
tmp.append(a)
with the result being in tmp.
Let's look at that innermost for loop. When you get the error, l equals [2, 3].
The interpreter is telling you that
for a, b in [2, 3]:
print a
isn't going to work. Why doesn't a equal 2 and b equal 3? Well, what if you do this:
for x in [2, 3]:
print x
What happens? First time through, x equals 2. Second time through, x equals 3. Notice that in each iteration of the loop, you're just getting out one integer. So if you replace x with a, b in the code, then the first time through the loop, the interpreter tries to do the following assignment:
a, b = 2
and that fails because 2 isn't iterable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With