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]
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.
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.
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.
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.
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.
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
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