Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to print list items

I would like to know if there is a better way to print all objects in a Python list than this :

myList = [Person("Foo"), Person("Bar")] print("\n".join(map(str, myList))) Foo Bar 

I read this way is not really good :

myList = [Person("Foo"), Person("Bar")] for p in myList:     print(p) 

Isn't there something like :

print(p) for p in myList 

If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?

like image 466
Guillaume Voiron Avatar asked Apr 02 '13 16:04

Guillaume Voiron


People also ask

Can you just print a list in Python?

Use the * Operator to Print Lists in Python Except for performing multiplication, the * operator is used to print each element of a list in one line with a space between each element.

How do I print a list as a string?

The most pythonic way of converting a list to string is by using the join() method. The join() method is used to facilitate this exact purpose. It takes in iterables, joins them, and returns them as a string. However, the values in the iterable should be of string data type.

How do I print a list on one line?

To print a list and display it in a single line, a straightforward solution is to iterate over each element in a for loop and print this element into the same line using the print() function with the end=' ' argument set to the empty space.


1 Answers

Assuming you are using Python 3.x:

print(*myList, sep='\n') 

You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.

With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:

for p in myList: print p 

For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:

print '\n'.join(str(p) for p in myList)  
like image 156
Andrew Clark Avatar answered Sep 30 '22 09:09

Andrew Clark