List comprehension returning values plus [None, None, None], why? [duplicate]
Im studying comprehensions. I get the print(x) part (i think. It prints the value of x that passes the 'in' test) but why is it also returning a list of None afterward?
>>> g
['a', 'x', 'p']
>>> [print(x) for x in g]
a
x
p
[None, None, None] #whats this?
Solution 1:
print
is a function (in Python3). It prints something to the screen, but returns None.
In Python2, print
is a statement. [print(x) for x in g]
would have raised a SyntaxError since only expressions, not statements, can be used in list comprehensions. A function call is an expression, which is why it is allowed in Python3. But as you can see, it is not very useful to use print
in a list comprehension, even if it is allowed.
Solution 2:
You use a list comprehension to print the items in the list, and then the list itself is printed. Try assigning the list to a variable instead.
>>> g
['a', 'x', 'p']
>>> x = [print(x) for x in g]
a
x
p
#
Now the list is in x and isnt printed. The list is still there...
>>> print(x)
[None, None, None]
>>> x
[None, None, None]
Solution 3:
[print(x) for x in g]
is equivalent to:
l = []
for i in g:
l.append(print(i))
return l
Print does the printing stuff, so you see the a, x and p, but it return None
so the list you get in the end is [None, None, None]