Search code examples
pythonlistprintinglist-comprehension

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 ?


Solution

  • Assuming you are using Python 3:

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

    This is a kind of unpacking. Details in the Python tutorial: Unpacking Argument Lists

    You can get the same behavior on Python 2 using from __future__ import print_function.

    With the print statement on Python 2 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 simple:

    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)