From my Python console
>>> numbers = [1,2,3]
>>> [print(x) for x in numbers]
1
2
3
[None, None, None]
Why does this print
If this behaviour of the Print function bothers, I suggest you don't use the Print function in the list comprehension, just use the following one-liner which is compact and more Pythonic:
>>> [x for x in [1,2,3]]
[1, 2, 3]
A list comprehension is not the right tool for the job at hand. It'll always return a list, and given that print()
evaluates to None
, the list is filled with None
values. A simple for
loop works better when we're not interested in creating a list of values, only in evaluating a function with no returned value:
for x in numbers:
print(x)
print is a function, it's just like
>>>def f(x):
...: pass
>>>[f(x) for x in numbers]
An ugly way of doing this is _=[print(i) for i in somelist]
It does work but is not encouraged:)
You can use the String Join() method and print the string. For example:
>>> print('\n'.join(numbers))
1
2
3
>>> print(', '.join(numbers))
1, 2, 3
>>> print(',\n'.join(numbers))
1,
2,
3
List comprehensions
always return a list
.
Based on this information, your print()
statement must wrap the whole list comprehension argument:
Numbers = [1, 2, 3]
print([x for x in Numbers])
If you want to print items of a list one by one, a for loop is more suitable for this matter.