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 ?
Assuming you are using Python 3.x:
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 a solution that uses
'\n'.join()
, I prefer list comprehensions and generators overmap()
so I would probably use the following:To display each content, I use:
Example of using in a function:
Hope I helped.
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
I use this all the time :
[print(a) for a in list]
will give a bunch of None types at the end though it prints out all the itemsExpanding @lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
Now the
", "
provides the separator (only between items, not at the end) and the formatting string'02d'
combined with%x
gives a formatted string for each itemx
- in this case, formatted as an integer with two digits, left-filled with zeros.