Pythonic way to print list items
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
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:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
[print(a) for a in list]
will give a bunch of None types at the end though it prints out all the items
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)