99

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)?

mechanical_meat
  • 144,326
  • 21
  • 211
  • 203
TIMEX
  • 217,272
  • 324
  • 727
  • 1,038

12 Answers12

185
from pprint import pprint
pprint(the_list)
John La Rooy
  • 263,347
  • 47
  • 334
  • 476
34

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
shxfee
  • 4,698
  • 4
  • 28
  • 28
30

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
MarcoP
  • 678
  • 5
  • 13
21

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!

Daren Thomas
  • 61,662
  • 38
  • 143
  • 192
Alex Martelli
  • 762,786
  • 156
  • 1,160
  • 1,345
8
import json
some_list = ['one', 'two', 'three', 'four']
print(json.dumps(some_list, indent=4))

Output:

[
    "one",
    "two",
    "three",
    "four"
]
Eyal Levin
  • 11,072
  • 5
  • 58
  • 51
3

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.

Iacchus
  • 1,930
  • 2
  • 22
  • 22
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

Community
  • 1
  • 1
El_Diablo
  • 21
  • 2
2

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))
aaronpenne
  • 505
  • 5
  • 9
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
TERMINATOR
  • 724
  • 5
  • 20
0

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.

Aaron D
  • 6,424
  • 3
  • 38
  • 45
0

you can also loop trough your list:

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

x = ["1",1,"a",8]
fun()
Skandix
  • 1,528
  • 5
  • 20
  • 29
vijay
  • 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 https://stackoverflow.com/questions/423379/using-global-variables-in-a-function – Valentino Mar 09 '19 at 13:33
0

If you want to just display a list as it is (with brackets), use:

print(list(the_list))
vitaliis
  • 2,865
  • 1
  • 7
  • 24