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 ?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With