# printing a two dimensional array in python

Posted on

### Question :

printing a two dimensional array in python

I have to print this python code in a 5×5 array the array should look like this :

``````0 1 4 (infinity) 3
1 0 2 (infinity) 4
4 2 0  1         5
(inf)(inf) 1 0   3
3 4 5   3        0
``````

can anyone help me print this table? using indices.

``````for k in range(n):
for i in range(n):
for j in range(n):
if A[i][k]+A[k][j]<A[i][j]:
A[i][j]=A[i][k]+A[k][j]
``````

A combination of list comprehensions and `str` joins can do the job:

``````inf = float('inf')
A = [[0,1,4,inf,3],
[1,0,2,inf,4],
[4,2,0,1,5],
[inf,inf,1,0,3],
[3,4,5,3,0]]

print('n'.join([''.join(['{:4}'.format(item) for item in row])
for row in A]))
``````

yields

``````   0   1   4 inf   3
1   0   2 inf   4
4   2   0   1   5
inf inf   1   0   3
3   4   5   3   0
``````

Using for-loops with indices is usually avoidable in Python, and is not considered “Pythonic” because it is less readable than its Pythonic cousin (see below). However, you could do this:

``````for i in range(n):
for j in range(n):
print '{:4}'.format(A[i][j]),
print
``````

The more Pythonic cousin would be:

``````for row in A:
for val in row:
print '{:4}'.format(val),
print
``````

However, this uses 30 print statements, whereas my original answer uses just one.

There is always the easy way.

``````import numpy as np
print(np.matrix(A))
``````

I used numpy to generate the array, but list of lists array should work similarly.

``````import numpy as np
def printArray(args):
print "t".join(args)

n = 10

Array = np.zeros(shape=(n,n)).astype('int')

for row in Array:
printArray([str(x) for x in row])
``````

If you want to only print certain indices:

``````import numpy as np
def printArray(args):
print "t".join(args)

n = 10

Array = np.zeros(shape=(n,n)).astype('int')

i_indices = [1,2,3]
j_indices = [2,3,4]

for i in i_indices:printArray([str(Array[i][j]) for j in j_indices])
``````

``````print(mat.__str__())
``````

where mat is variable refering to your matrix object

``````for i in A:
print('t'.join(map(str, i)))
``````

using indices, for loops and formatting:

``````import numpy as np

def printMatrix(a):
print "Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]"
rows = a.shape[0]
cols = a.shape[1]
for i in range(0,rows):
for j in range(0,cols):
print "%6.f" %a[i,j],
print
print

def printMatrixE(a):
print "Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]"
rows = a.shape[0]
cols = a.shape[1]
for i in range(0,rows):
for j in range(0,cols):
print("%6.3f" %a[i,j]),
print
print

inf = float('inf')
A = np.array( [[0,1.,4.,inf,3],
[1,0,2,inf,4],
[4,2,0,1,5],
[inf,inf,1,0,3],
[3,4,5,3,0]])

printMatrix(A)
printMatrixE(A)
``````

which yields the output:

``````Matrix[5][5]
0      1      4    inf      3
1      0      2    inf      4
4      2      0      1      5
inf    inf      1      0      3
3      4      5      3      0

Matrix[5][5]
0.000  1.000  4.000    inf  3.000
1.000  0.000  2.000    inf  4.000
4.000  2.000  0.000  1.000  5.000
inf    inf  1.000  0.000  3.000
3.000  4.000  5.000  3.000  0.000
``````

In addition to the simple print answer, you can actually customise the print output through the use of the numpy.set_printoptions function.

Prerequisites:

``````>>> import numpy as np
>>> inf = np.float('inf')
>>> A = np.array([[0,1,4,inf,3],[1,0,2,inf,4],[4,2,0,1,5],[inf,inf,1,0,3],[3,4,5,3,0]])
``````

The following option:

``````>>> np.set_printoptions(infstr="(infinity)")
``````

Results in:

``````>>> print(A)
[[        0.         1.         4. (infinity)         3.]
[        1.         0.         2. (infinity)         4.]
[        4.         2.         0.         1.         5.]
[(infinity) (infinity)         1.         0.         3.]
[        3.         4.         5.         3.         0.]]
``````

The following option:

``````>>> np.set_printoptions(formatter={'float': "t{: 0.0f}t".format})
``````

Results in:

``````>>> print(A)
[[   0       1       4       inf     3  ]
[   1       0       2       inf     4  ]
[   4       2       0       1       5  ]
[   inf     inf     1       0       3  ]
[   3       4       5       3       0  ]]

``````

If you just want to have a specific string output for a specific array, the function numpy.array2string is also available.