Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many for in one line in python generator

I can't understand code with multi "for"s in one generator like this, I searched Google and didn't find any answer:

print [j for i in [[1,2],[4,6]] for j in i ]
# will print [1, 2, 4, 6]

print [j for j in i for i in [[1,2],[4,6]] ]
# will print [4, 4, 6, 6]

What is the difference?

How to interpret code like this?

like image 240
Statham Avatar asked Jul 21 '26 10:07

Statham


2 Answers

Hopefully the expansions will help you reason with the code. It's a lot more readable this way, in my opinion. I'm printing one element at a time instead of the whole list.

print [j for i in [[1, 2], [4, 6]] for j in i]

is equivalent to

for i in [[1, 2], [4, 6]]:
    for j in i:
        print j

As a result i = [4, 6].

Now,

print [j for j in i for i in [[1,2],[4,6]]]

is equivalent to

for j in i: # Remember, i = [4, 6]
    for i in [[1, 2], [4, 6]]:
        print j

The second generater is error, but in your code scripts, the second generator, the i will be [4, 6] after your run the first generator, so the second will output [4, 4, 6, 6]

like image 42
Charles Cao Avatar answered Jul 23 '26 23:07

Charles Cao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!