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?
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions.
Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.
List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
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')
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