Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Comprehension: why is this a syntax error?

Why is print(x) here not valid (SyntaxError) in the following list-comprehension?

my_list=[1,2,3] [print(my_item) for my_item in my_list] 

To contrast - the following doesn't give a syntax error:

def my_func(x):     print(x) [my_func(my_item) for my_item in my_list] 
like image 353
monojohnny Avatar asked Jan 26 '10 17:01

monojohnny


People also ask

What is the syntax for list comprehension?

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

Why am I getting a syntax error?

A syntax error occurs when a programmer writes an incorrect line of code. Most syntax errors involve missing punctuation or a misspelled name. If there is a syntax error in a compiled or interpreted programming language, then the code won't work.

How do you fix a syntax error in Python?

You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

What is comprehension syntax in Python?

List comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a very concise way to create a new list by performing an operation on each item in the existing list. List comprehension is considerably faster than processing a list using the for loop.


2 Answers

Because print is not a function, it's a statement, and you can't have them in expressions. This gets more obvious if you use normal Python 2 syntax:

my_list=[1,2,3] [print my_item for my_item in my_list] 

That doesn't look quite right. :) The parenthesizes around my_item tricks you.

This has changed in Python 3, btw, where print is a function, where your code works just fine.

like image 116
Lennart Regebro Avatar answered Oct 09 '22 05:10

Lennart Regebro


list comprehension are designed to create a list. So using print inside it will give an error no-matter we use print() or print in 2.7 or 3.x. The code

[my_item for my_item in my_list]  

makes a new object of type list.

print [my_item for my_item in my_list] 

prints out this new list as a whole

refer : here

like image 38
Ishan Khare Avatar answered Oct 09 '22 05:10

Ishan Khare