From Python 3.6 prompt:
>>> [print(i) for i in range(3)]
0
1
2
[None, None, None]
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.
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]
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