Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python list comprehension print a list of "None"s in the end? [duplicate]

From Python 3.6 prompt:

>>> [print(i) for i in range(3)]
0
1
2
[None, None, None]
like image 944
Vikas Zingade Avatar asked Oct 16 '25 06:10

Vikas Zingade


2 Answers

A list comprehension creates a list containing the results of evaluating the expression for each iteration. As well as the "side-effect" of printing out whatever you give it, the print function returns None, so that is what gets stored in the list.

Since you're in an interactive console, the return value is printed out at the end. If you ran this as a script, the output wouldn't include [None, None, None].

If you're wanting to loop over 0, 1, 2 and print them out, I'm afraid you have to do it as a proper for-loop:

for i in range(3):
    print(i)

Though I fully empathise with the desire to use the neat one-line syntax of a list comprehension! 😞


As other people have commented, you can achieve the same effect by constructing the list (using a list comprehension) and then printing that out:

print(*[i for i in range(3)], sep="\n")

You need the sep argument if you want them on a new line each; without it they'll be on one line, each separated by a space.

like image 150
Tim Avatar answered Oct 18 '25 21:10

Tim


When you put the print statement there, it prints each of the value, then prints the list which has no values in it.

>>> this = print([(i) for i in range(3)])
[0, 1, 2]
>>> print(this)
None
>>> 

This should show you the problem. What you want to use is

>>> [(i) for i in range(3)]
[0, 1, 2]
like image 30
DUDANF Avatar answered Oct 18 '25 21:10

DUDANF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!