From my Python console
>>> numbers = [1,2,3]
>>> [print(x) for x in numbers]
1
2
3
[None, None, None]
Why does this print
3 ways to print using list comps:
print([(i) or i for i in range(4)])
def printVal(val): print("val: ", val) return val
[printVal(i) or i for i in range(4)]
[print(i) or i for i in range(4)]
The print
function returns None
. The list comprehension is applying the function to each element of the list (outputting the results), but collecting those None
objects into the results array. The Python interpreter is printing that array.
print
is a function in Python 3, which returns a None
. Since you are calling it three times, it constructs a list of three None
elements.
You should restructure your loop to send arguments to print()
:
>>> numbers = [1,2,3]
>>> print(*(x for x in numbers), sep='\n')
Note that you don't need the explicit generator. Just unpack the list
itself:
>>> numbers = [1,2,3]
>>> print(*numbers, sep='\n')