List comprehension returning values plus [None, None, None], why?

Question:

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? 
Asked By: jason

||

Answers:

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.

Answered By: unutbu
[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]

Answered By: Viktor Kerkez

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]
Answered By: tdelaney

I think you are conflating a list comprehension with str.join method.

A list comprehension always produces a new list. Three ways list may be produced that is the same as g

>>> [x for x in 'axp']
['a', 'x', 'p']
>>> [x[0] for x in ['alpha', 'xray', 'papa']]
['a', 'x', 'p']
>>> list('axp')
['a', 'x', 'p']

Since g is already strings, you use join to produce a single string to print it:

>>> g=['a', 'x', 'p']
>>> ''.join(g)
'axp'

To print it, just use join with the separator desired:

>>> print('n'.join(g))
a
x
p

You would need to use a comprehension if the elements of the list are not compatible with join by being strings:

>>> li=[1,2,3]
>>> 'n'.join(li)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
>>> print('n'.join(str(e) for e in li))
1
2
3
Answered By: dawg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.