Printing using list comprehension

From my Python console

>>> numbers = [1,2,3]
>>> [print(x) for x in numbers]
1
2
3
[None, None, None]

Why does this print three none’s at the end?

Answer

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)

Leave a Reply

Your email address will not be published. Required fields are marked *