Creating and Printing 2 Dimensional Arrays Using Python

Learn python programming in 12 lessons


A matrix in Python is represented as a 2 dimensional array.

Creating a matrix is done by creating a single list of lists. In other words, a matrix in Python is an array that contains other arrays. Here are examples of matrices of different sizes:
2x2 -- [[0,0], [0,0]]
3x3 -- [[0,0,0], [0,0,0], [0,0,0]]
4x4 -- [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]

The steps you need to take when creating an nxn matrix are as follow
create a single empty list
repeat the steps below n times
           create another list with a single element
           multiply that list by n
           add that list to the outer list

Below is the Python code to create an nxn matrix


def createMatrix(n):
    """creates a matrix of size nxn"""
   
    matrix = [] # the outer matrix
   
    for i in range (n):
        matrix.append ([0] * n) #creates a 2-d list of size nxn
   
    return matrix

If the function above is executed, the output would look like this

createMatrix(1)
[[0]]
createMatrix(2)
[[0, 0], [0, 0]]
createMatrix(3)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
createMatrix(4)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
createMatrix(5)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]


When it comes to printing the matrix, you would prefer to see rows and columns on the screen. This is achieved by printing each element in the list separately one list under the other. The Python code below does just that.


def printMatrix(matrix):
    """print out a nxn matrix"""
   
    for i in range( len(matrix) ): # for the rows
        for j in range( len(matrix) ): #for the columns
            print( matrix[i][j], end=' ' ) # prints one row
        print() # move to the next level

The output of the following function is as follow


printMatrix(createMatrix(2))
0 0
0 0
printMatrix(createMatrix(3))
0 0 0
0 0 0
0 0 0
printMatrix(createMatrix(4))
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
printMatrix(createMatrix(5))
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

Below is the full code including the main method


 def createMatrix(n):
    """creates a matrix of size nxn"""
   
    matrix = [] # the outer matrix
   
    for i in range (n):
        matrix.append ([0] * n) #creates a 2-d list of size nxn
   
    return matrix


def printMatrix(matrix):
    """print out a nxn matrix"""
   
    for i in range( len(matrix) ): # for the rows
        for j in range( len(matrix) ): #for the columns
            print( matrix[i][j], end=' ' ) # prints one row
        print() # move to the next level
       
def main():
    print("\n\n2x2 matrix\n")
    printMatrix(createMatrix(2))
    print("\n\n3x3 matrix\n")
    printMatrix(createMatrix(3))
    print("\n\n4x4 matrix\n")
    printMatrix(createMatrix(4))
    print("\n\n5x5 matrix\n")
    printMatrix(createMatrix(5))


if __name__ == "__main__":
    main()

Share your thoughts