banner

© 2004-21 ict4u.net

Using a 2D List

Initialise a 2D list using a loop:

This code uses python lists to create a list within a list to mimic the traditional view of a matrix as a set of rows and columns.
Don't forget that the index starts at 0 not 1!

This link will help you visualise how a list looks in terms of rows and columns

The code snippet below sets up a list and then displays an unformatted version of the contents

#
# Create a 2D list in python
#
#First define the initial size of the matrix
Cols= 8
Rows= 10


def CreateMatrix(Col,Row):
    # Col and Row  mimic the traditional view of a matrix as a set of rows and columns
    # create the matrix as a list within list
    Matrix = [["~" for x in range(Col)] for y in range(Row)]
    return Matrix

myMatrix=CreateMatrix(Cols,Rows)
print (myMatrix)