143

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 ?

Guillaume Voiron
  • 1,785
  • 2
  • 15
  • 16
  • 5
    Where did you get the impression that using `for p in myList` was "not really good" ? – Jon Clements Apr 02 '13 at 16:26
  • @JonClements : http://chrisarndt.de/talks/rupy/2008/output/slides.html – Guillaume Voiron Apr 02 '13 at 16:33
  • @Guillaume You sure about that? There's a slide that says "**Use `in` where possible**. Good: `for key in d: print key`". Link is dead though so here's [an archive link](https://web.archive.org/web/20121027131509/http://chrisarndt.de/talks/rupy/2008/output/slides.html). – wjandrea Nov 11 '21 at 01:54

13 Answers13

280

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) 
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • in python 2x using map is slightly faster than using join on a list comprehension. – Juan Carlos Moreno Apr 02 '13 at 16:33
  • 1
    Why the downvote, is it really due to the speed difference between `map()` and a generator? [Python's creator also happens to prefer comprehensions and generators over `map()`](http://www.artima.com/weblogs/viewpost.jsp?thread=98196). – Andrew Clark Apr 02 '13 at 16:37
  • I didn't down vote you. I am familiar with that post from GVR which was his way of saying, back then, how future versions of python were not going to include it but, they ended up staying. – Juan Carlos Moreno Apr 02 '13 at 16:43
  • 1
    They did stay in Python 3.x, but his point in that article is that `[F(x) for x in S]` is more clear than `map(F, S)`. Performance is not addressed there, but I would expect the speed difference to be negligible. Anyway I was just confused about the downvote, sorry I assumed it was you! – Andrew Clark Apr 02 '13 at 16:48
  • Can this be combined with other strings in a single print statement? – Eliezer Miron Sep 07 '16 at 15:31
  • 1
    @EliezerMiron Yes, for example, `print('baz', *myList, 'qux', sep='-')` -> `baz-foo-bar-qux`. (The ability to have positional arguments after a starred argument was added in Python 3.5 per [the docs on calls](https://docs.python.org/3/reference/expressions.html?highlight=unpacking#calls).) – wjandrea Mar 10 '23 at 16:31
30

I use this all the time:

l = [1,2,3,7] 
print "".join([str(x) for x in l])
wjandrea
  • 28,235
  • 9
  • 60
  • 81
lucasg
  • 10,734
  • 4
  • 35
  • 57
8

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

rassa45
  • 3,482
  • 1
  • 29
  • 43
  • this is what I've been using so far. It's one line, very clear and expresive, but linter complaints "Expression is assigned to nothing" – alete Jan 19 '19 at 04:52
  • 1
    If you want to troll the linter, you can make a separate function that prints it out and returns some stupid value and call that function in the list comprehension – rassa45 Jan 19 '19 at 18:19
  • [Don't use a list comprehension for side effects](/a/5753614/4518341) for exactly the reason you mentioned: it creates a bunch of junk as well. Just use a plain for-loop, like `for a in list: print(a)` – wjandrea Mar 10 '23 at 15:32
3

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.

gukoff
  • 2,112
  • 3
  • 18
  • 30
3

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.

Floris
  • 45,857
  • 6
  • 70
  • 122
1

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.')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
ShinyMemes
  • 42
  • 1
  • 2
    Just as a note, please check the answer above you. You use a range, which provides an index value, i, yet you use another variable, indexval, as your index?? You're fighting against the simplicity of python. for val in my_list: print val does the same as what you have – BretD Jun 27 '17 at 22:23
  • That function is atrocious. If you pass in `mylist` and specify *any* `startat` value other than 0, -1, or -2, it errors. Plus, it seems glaringly obvious that `startat` should default to 0, and that there's no need for `indexval` (like BretD says) when you can just do `mylist[i+startat]` instead. For printing a list starting from a certain point, you can simply use slicing, like `for val in my_list[startval:]: print(val)` – wjandrea Mar 10 '23 at 16:13
  • Also, `listname` represents the list itself, not the name of the list (like a string), so call it something else. And it's not even used in the function body; `mylist` is instead. – wjandrea Mar 10 '23 at 16:22
  • (Not trying to be mean, just trying to tell people who maybe don't know Python that this code is bad, so don't use it.) – wjandrea Mar 10 '23 at 16:36
0

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' % myList)

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Old printf-style formatting is no longer recommended (see the note [here in the docs](https://docs.python.org/3/library/stdtypes.html#old-string-formatting)). It's not even necessary in this case: `print('myList is', myList)`. Alternatively, newer f-strings let you get the variable name and value together more easily: `print(f'{myList = }')` -> `myList = ['foo', 'bar']` – wjandrea Mar 10 '23 at 15:48
0

I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...

x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing

while x <= (userInput - 1): #loops as many times as the user inputs above
    password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
    x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
    passwordText = passwordText + password[up]
    up = up+1 # same as x increase


print(passwordText)

Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • This doesn't even print a list, it prints a string. There *is* a list involved in the code, but it's not relevant to the printing part. – wjandrea Mar 10 '23 at 16:00
0

To print each element of a given list using a single line code

 for i in result: print(i)
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
0

you can try doing this: this will also print it as a string

print(''.join([p for p in myList]))

or if you want to a make it print a newline every time it prints something

print(''.join([p+'\n' for p in myList]))
aaossa
  • 3,763
  • 2
  • 21
  • 34
Adrian
  • 33
  • 1
  • 7
-1

Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:

mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']

print(f"There are {len(mylist):d} items in this lorem list: {mylist}")

Running this produces the following output:

There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum', 'dolor', 'sit', 'amet']

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Aethalides
  • 367
  • 5
  • 12
-1

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

Gaurav Singhal
  • 998
  • 2
  • 10
  • 25
-1

You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:

sample_list = ['Python', 'is', 'Easy']

for i in range(0, len(sample_list)):

      print(sample_list[i])

Reference : https://favtutor.com/blogs/print-list-python

Cody peltz
  • 49
  • 1
  • 2