Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a matrix using Python [duplicate]

Tags:

python

I am trying to create a matrix and then print it using python with the following expected output:

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

The code follows:

    matrix=[[]]
    matrix = [[0 for x in range(4)] for x in range(4)]
    print matrix

But the output comes as:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Please tell me why I'm getting this type of output and help with the correct one

like image 319
Meghanab Avatar asked Apr 25 '26 06:04

Meghanab


1 Answers

What you are getting is the correct representation of a matrix. You have created a list that contains 4 lists, each list containing 4 '0's. If you want to print it differently then you have some options, but what you are printing is the representation of the above mentioned data structure.

for row in matrix:
  print ' '.join(map(str,row))

this should work for you.

like image 138
bravosierra99 Avatar answered Apr 27 '26 19:04

bravosierra99