How to Print a List in Python "Nicely"

How to print a list in Python nicely

from pprint import pprint
pprint(the_list)

How to print a list more nicely?

Although not designed for it, the standard-library module in Python 3 cmd has a utility for printing a list of strings in multiple columns

import cmd
cli = cmd.Cmd()
cli.columnize(foolist, displaywidth=80)

You even then have the option of specifying the output location, with cmd.Cmd(stdout=my_stream)

Printing Lists as Tabular Data

Some ad-hoc code:

row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
print(row_format.format(team, *row))

This relies on str.format() and the Format Specification Mini-Language.

How do I print a list of doubles nicely in python?

have you tried "% .2f" (note: the space)? – J.F. Sebastian

Print list of lists in separate lines

Iterate through every sub-list in your original list and unpack it in the print call with *:

a = [[1, 3, 4], [2, 5, 7]]
for s in a:
print(*s)

The separation is by default set to ' ' so there's no need to explicitly provide it. This prints:

1 3 4
2 5 7

In your approach you were iterating for every element in every sub-list and printing that individually. By using print(*s) you unpack the list inside the print call, this essentially translates to:

print(1, 3, 4)  # for s = [1, 3, 4]
print(2, 5, 7) # for s = [2, 5, 7]

Python: Is there a way to pretty-print a list?

You can justify according to the longest word:

longest = max([len(x[0]) for x in data])

for j in data:
a = j[0].ljust(longest)
b = str(j[1])
print(' '.join([a, b]))

Here is the output:

MSG1        3030
MEMORYSPACE 3039
NEWLINE 3040
NEG48 3041

How to print out a dictionary nicely in Python?

I like the pprint module (Pretty Print) included in Python. It can be used to either print the object, or format a nice string version of it.

import pprint

# Prints the nicely formatted dictionary
pprint.pprint(dictionary)

# Sets 'pretty_dict_str' to the formatted string value
pretty_dict_str = pprint.pformat(dictionary)

But it sounds like you are printing out an inventory, which users will likely want shown as something more like the following:

def print_inventory(dct):
print("Items held:")
for item, amount in dct.items(): # dct.iteritems() in Python 2
print("{} ({})".format(item, amount))

inventory = {
"shovels": 3,
"sticks": 2,
"dogs": 1,
}

print_inventory(inventory)

which prints:

Items held:
shovels (3)
sticks (2)
dogs (1)

How to print out list of elements in a designated format nicely?

If the two sequences are of the same length:

list1 = ["a", "b", "c"]
list2 = ["1", "2", "3"]

print(', '.join('{}: {}'.format(a, b) for a, b in zip(list1, list2)))

Outputs:

a: 1, b: 2, c: 3

In Python 3.6+, you can use an f-string to do it a little more succinctly:

print(', '.join(f'{a}: {b}' for a, b in zip(list1, list2)))


Related Topics



Leave a reply



Submit