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

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

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

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

Method 4

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x