Pretty print 2D list?

PythonMatrix

Python Problem Overview


Is there a simple, built-in way to print a 2D Python list as a 2D matrix?

So this:

[["A", "B"], ["C", "D"]]

would become something like

A    B
C    D

I found the pprint module, but it doesn't seem to do what I want.

Python Solutions


Solution 1 - Python

To make things interesting, let's try with a bigger matrix:

matrix = [
   ["Ah!",  "We do have some Camembert", "sir"],
   ["It's a bit", "runny", "sir"],
   ["Well,",  "as a matter of fact it's", "very runny, sir"],
   ["I think it's runnier",  "than you",  "like it, sir"]
]
 
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print '\n'.join(table)

Output:

Ah!                 	We do have some Camembert	sir            
It's a bit          	runny                    	sir            
Well,               	as a matter of fact it's 	very runny, sir
I think it's runnier	than you                 	like it, sir  

UPD: for multiline cells, something like this should work:

text = [
    ["Ah!",  "We do have\nsome Camembert", "sir"],
    ["It's a bit", "runny", "sir"],
    ["Well,",  "as a matter\nof fact it's", "very runny,\nsir"],
    ["I think it's\nrunnier",  "than you",  "like it,\nsir"]
]

from itertools import chain, izip_longest

matrix = chain.from_iterable(
    izip_longest(
        *(x.splitlines() for x in y), 
        fillvalue='') 
    for y in text)

And then apply the above code.

See also http://pypi.python.org/pypi/texttable

Solution 2 - Python

If you can use Pandas (Python Data Analysis Library) you can pretty-print a 2D matrix by converting it to a DataFrame object:

from pandas import *
x = [["A", "B"], ["C", "D"]]
print DataFrame(x)

   0  1
0  A  B
1  C  D

Solution 3 - Python

For Python 3 without any third part libs:

matrix = [["A", "B"], ["C", "D"]]

print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in matrix]))

Output

A	B
C	D

Solution 4 - Python

You can always use numpy:

import numpy as np
A = [['A', 'B'], ['C', 'D']]
print(np.matrix(A))

Output:

[['A' 'B']
 ['C' 'D']]

Solution 5 - Python

Just to provide a simpler alternative to print('\n'.join(\['\t'.join(\[str(cell) for cell in row\]) for row in matrix\])) :

matrix = [["A", "B"], ["C", "D"]]
for row in matrix:
    print(*row)

Explanation *row unpacks row, so print("A", "B") is called when row is ["A", "B"], for example.

Note Both answers will only be formatted nicely if each column has the same width. To change the delimiter, use the sep keyword. For example,

for row in matrix:
    print(*row, sep=', ')

will print

A, B
C, D

instead.

One-liner without a for loop

print(*(' '.join(row) for row in matrix), sep='\n')

' '.join(row) for row in matrix) returns a string for every row, e.g. A B when row is ["A", "B"].

*(' '.join(row) for row in matrix), sep='\n') unpacks the generator returning the sequence 'A B', 'C D', so that print('A B', 'C D', sep='\n') is called for the example matrix given.

Solution 6 - Python

A more lightweight approach than pandas is to use the prettytable module

from prettytable import PrettyTable

x = [["A", "B"], ["C", "D"]]

p = PrettyTable()
for row in x:
    p.add_row(row)

print p.get_string(header=False, border=False)

yields:

A B
C D

prettytable has lots of options to format your output in different ways.

See https://code.google.com/p/prettytable/ for more info

Solution 7 - Python

If you're using a Notebook/IPython environment, then sympy can print pleasing matrices using IPython.display:

import numpy as np
from sympy import Matrix, init_printing
init_printing()

print(np.random.random((3,3)))
display(np.random.random((3,3)))
display(Matrix(np.random.random((3,3))))

enter image description here

Solution 8 - Python

I would also recommend tabulate, which can optionally print headers too:

from tabulate import tabulate

lst = [['London', 20],['Paris', 30]]
print(tabulate(lst, headers=['City', 'Temperature']))

:

City      Temperature
------  -------------
London             20
Paris              30

Solution 9 - Python

Without any third party libraries, you could do:

matrix = [["A", "B"], ["C", "D"]]
print(*matrix, sep="\n")

Output:

['A', 'B']
['C', 'D']

Solution 10 - Python

You can update print's end=' ' so that it prints space instead of '\n' in the inner loop and outer loop can have print().

a=[["a","b"],["c","d"]]
for i in a:
  for j in i:
    print(j, end=' ')
  print()

I found this solution from here.

Solution 11 - Python

See the following code.

# Define an empty list (intended to be used as a matrix)
matrix = [] 
matrix.append([1, 2, 3, 4])
matrix.append([4, 6, 7, 8])
print matrix
# Now just print out the two rows separately
print matrix[0]
print matrix[1]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhoubysoftView Question on Stackoverflow
Solution 1 - PythongeorgView Answer on Stackoverflow
Solution 2 - PythonstenView Answer on Stackoverflow
Solution 3 - PythonRodrigo LópezView Answer on Stackoverflow
Solution 4 - PythonSouradeep NandaView Answer on Stackoverflow
Solution 5 - PythonAnonymousView Answer on Stackoverflow
Solution 6 - PythonDov GrobgeldView Answer on Stackoverflow
Solution 7 - PythonZSGView Answer on Stackoverflow
Solution 8 - PythonReveilleView Answer on Stackoverflow
Solution 9 - PythonOmarView Answer on Stackoverflow
Solution 10 - PythonSandeepView Answer on Stackoverflow
Solution 11 - PythonjfconroyView Answer on Stackoverflow