Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: print i for i in list

Tags:

python

When I printed a list, I got a syntax error when using this method:

print i for i in [1,2,3]

I knew this is ok when using this method:

for i in [1, 2, 3]:
    print i

and I knew that

(i for i in [1, 2, 3])

is a generator object, but I just don't get it that why

print i for i in [1, 2, 3] 

does't work. Can anyone give me a clue?

like image 292
Rain Zeng Avatar asked Aug 26 '26 05:08

Rain Zeng


1 Answers

The list comprehension syntax x for x in ... requires brackets around it. That's a syntactic rule of Python, just like requiring indentation, or requiring a colon after if or whatever. i for i in [1, 2, 3] by itself is not valid syntax. You need either [i for i in [1, 2, 3]] (for a list comprehension) or (i for i in [1, 2, 3]) (for a generator comprehension).

like image 190
BrenBarn Avatar answered Sep 04 '26 00:09

BrenBarn



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!