How to print a list in Python "nicely"

Viewed 210989

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

11 Answers
import json
some_list = ['one', 'two', 'three', 'four']
print(json.dumps(some_list, indent=4))

Output:

[
    "one",
    "two",
    "three",
    "four"
]

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

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

you can also loop trough your list:

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

x = ["1",1,"a",8]
fun()
Related