Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing using list comprehension

Tags:

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?

like image 817
Apollo Avatar asked May 07 '16 03:05

Apollo


People also ask

What is the use of list comprehension in Python?

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.

What does list comprehension mean?

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.

Are list comprehensions more efficient?

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.

Why are list comprehensions faster than for loops?

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.


1 Answers

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') 
like image 74
TigerhawkT3 Avatar answered Sep 28 '22 04:09

TigerhawkT3