How to print a list in Python "nicely"
Asked Answered
S

11

153

In PHP, I can do this:

echo '<pre>'
print_r($array);
echo '</pre>'

In Python, I currently just do this:

print the_list

However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?

Shorten answered 6/10, 2009 at 4:55 Comment(0)
H
274
from pprint import pprint
pprint(the_list)
Hygienic answered 6/10, 2009 at 4:57 Comment(7)
How ot pretty print to a file?Durer
Why not just use import pprint?Longwise
@clankill3r, then you need to use pprint.pprint(the_list) usually it's just a matter of personal preference. I chose to have the extra clutter in the import line in this case.Hygienic
@Mawg, you can specify an output stream using stream=, the default is stdout. docs.python.org/3/library/pprint.htmlHygienic
It's enabled by default in Ipython REPLBrunel
@Longwise from pprint import pprint is equivalent to import pprint.pprint as pprint then you use the pprint alias as usual.Voiture
If your list elements are long enough to wrap, the output may look better using the width option, as in pprint(the_list, width=100).Buchenwald
D
95

Simply by "unpacking" the list in the print function argument and using a newline (\n) as separator.

print(*lst, sep='\n')

lst = ['foo', 'bar', 'spam', 'egg']
print(*lst, sep='\n')

foo
bar
spam
egg
Decay answered 4/2, 2016 at 20:51 Comment(4)
Nice but unfortunately only available in Python 3.Capstone
If you really need it in Python 2.7, you could still import the print function from future from __future__ import print_function Thanks for the comment.Decay
the * is vital, got me for a sec x)Dragelin
IMO in 2021 where Python 3 is the standard, this should be the accepted answerGarate
E
45

A quick hack while debugging that works without having to import pprint would be to join the list on '\n'.

>>> lst = ['foo', 'bar', 'spam', 'egg']
>>> print '\n'.join(lst)
foo
bar
spam
egg
Exeter answered 8/3, 2015 at 15:35 Comment(3)
TypeError when the list contains None.Conversazione
Easy solution and can be formated like `"list: * {}".format('\n * '.join(lst))Ridicule
when your list contains something other then strings you should do print '\n'.join(map(str, lst))Resplendent
F
23

You mean something like...:

>>> print L
['this', 'is', 'a', ['and', 'a', 'sublist', 'too'], 'list', 'including', 'many', 'words', 'in', 'it']
>>> import pprint
>>> pprint.pprint(L)
['this',
 'is',
 'a',
 ['and', 'a', 'sublist', 'too'],
 'list',
 'including',
 'many',
 'words',
 'in',
 'it']
>>> 

...? From your cursory description, standard library module pprint is the first thing that comes to mind; however, if you can describe example inputs and outputs (so that one doesn't have to learn PHP in order to help you;-), it may be possible for us to offer more specific help!

Foresee answered 6/10, 2009 at 5:2 Comment(0)
A
21
import json
some_list = ['one', 'two', 'three', 'four']
print(json.dumps(some_list, indent=4))

Output:

[
    "one",
    "two",
    "three",
    "four"
]
Antoinetteanton answered 19/2, 2019 at 14:55 Comment(1)
json.dumps adds new line characters in my values for some reason..Hope
H
4

https://docs.python.org/3/library/pprint.html

If you need the text (for using with curses for example):

import pprint

myObject = []

myText = pprint.pformat(myObject)

Then myText variable will something alike php var_dump or print_r. Check the documentation for more options, arguments.

Heavyladen answered 12/12, 2015 at 14:8 Comment(0)
P
4

For Python 3, I do the same kind of thing as shxfee's answer:

def print_list(my_list):
    print('\n'.join(my_list))

a = ['foo', 'bar', 'baz']
print_list(a)

which outputs

foo
bar
baz

As an aside, I use a similar helper function to quickly see columns in a pandas DataFrame

def print_cols(df):
    print('\n'.join(df.columns))
Pilferage answered 29/6, 2018 at 21:0 Comment(0)
P
2

As the other answers suggest pprint module does the trick.
Nonetheless, in case of debugging where you might need to put the entire list into some log file, one might have to use pformat method along with module logging along with pprint.

import logging
from pprint import pformat

logger = logging.getLogger('newlogger')
handler = logging.FileHandler('newlogger.log')

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)

logger.addHandler(handler) 
logger.setLevel(logging.WARNING)

data = [ (i, { '1':'one',
           '2':'two',
           '3':'three',
           '4':'four',
           '5':'five',
           '6':'six',
           '7':'seven',
           '8':'eight',
           })
         for i in xrange(3)
      ]

logger.error(pformat(data))

And if you need to directly log it to a File, one would have to specify an output stream, using the stream keyword. Ref

from pprint import pprint

with open('output.txt', 'wt') as out:
   pprint(myTree, stream=out)

See Stefano Sanfilippo's answer

Panpipe answered 2/12, 2016 at 8:4 Comment(0)
D
2

As other answers have mentioned, pprint is a great module that will do what you want. However if you don't want to import it and just want to print debugging output during development, you can approximate its output.

Some of the other answers work fine for strings, but if you try them with a class object it will give you the error TypeError: sequence item 0: expected string, instance found.

For more complex objects, make sure the class has a __repr__ method that prints the property information you want:

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __repr__(self):
        return "Foo - (%r)" % self.bar

And then when you want to print the output, simply map your list to the str function like this:

l = [Foo(10), Foo(20), Foo("A string"), Foo(2.4)]
print "[%s]" % ",\n ".join(map(str,l))

outputs:

 [Foo - (10),
  Foo - (20),
  Foo - ('A string'),
  Foo - (2.4)]

You can also do things like override the __repr__ method of list to get a form of nested pretty printing:

class my_list(list):
    def __repr__(self):
        return "[%s]" % ",\n ".join(map(str, self))

a = my_list(["first", 2, my_list(["another", "list", "here"]), "last"])
print a

gives

[first,
 2,
 [another,
 list,
 here],
 last]

Unfortunately no second-level indentation but for a quick debug it can be useful.

Dragone answered 14/4, 2017 at 20:4 Comment(0)
J
2

This is a method from raw python that I use very often!

The code looks like this:

list = ["a", "b", "c", "d", "e", "f", "g"]

for i in range(len(list)):
    print(list[i])

output:

a
b
c
d
e
f
g
Jacky answered 17/1, 2021 at 10:51 Comment(0)
M
-1

you can also loop trough your list:

def fun():
  for i in x:
    print(i)

x = ["1",1,"a",8]
fun()
Moony answered 9/3, 2019 at 13:20 Comment(1)
Hello! Please format the code, as it is, it's not easy to follow. Also, global is not meant to be used it that way in python. See #423879Jessiajessica

© 2022 - 2024 — McMap. All rights reserved.