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)))

I read this way is not really good :

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

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 ?

4/2/2013 4:24:15 PM

Accepted Answer

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) 
4/2/2013 4:40:30 PM

I use this all the time :


l = [1,2,3,7] 
print "".join([str(x) for x in l])

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow