Pythonic way to print list items

Posted on

Solving problem is about exposing yourself to as many situations as possible like Pythonic way to print list items and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Pythonic way to print list items, which can be followed any time. Take easy to follow this discuss.

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 ?

Answer #1:

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)
Answered By: Andrew Clark

Answer #2:

I use this all the time :

#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
Answered By: lucasg

Answer #3:

[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items

Answered By: ytpillai

Answer #4:

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.

Answered By: gukoff

Answer #5:

Expanding @lucasg’s answer (inspired by the comment it received):

To get a formatted list output, you can do something along these lines:

l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05

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 item x – in this case, formatted as an integer with two digits, left-filled with zeros.

Answered By: Floris

Answer #6:

To display each content, I use:

mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
    print(mylist[indexval])
    indexval += 1

Example of using in a function:

def showAll(listname, startat):
   indexval = startat
   try:
      for i in range(len(mylist)):
         print(mylist[indexval])
         indexval = indexval + 1
   except IndexError:
      print('That index value you gave is out of range.')

Hope I helped.

Answered By: ShinyMemes

Answer #7:

I think this is the most convenient if you just want to see the content in the list:

myList = ['foo', 'bar']
print('myList is %s' % str(myList))

Simple, easy to read and can be used together with format string.

Answered By: Rongzhao Zhang

Answer #8:

OP’s question is: does something like following exists, if not then why

print(p) for p in myList # doesn't work, OP's intuition

answer is, it does exist which is:

[p for p in myList] #works perfectly

Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this

Answered By: Gaurav Singhal

Leave a Reply

Your email address will not be published.