ICS4U – Python Two Dimensional Lists

ICS4U Learning Goals

In this ICS4U Grade 12 Computer Science lesson you will be learning how to

  • Access data in Two Dimensional Lists
  • Store / Change data in Two Dimensional Lists

Two Dimensional Data

Sometimes data naturally occurs in two dimensional form.  

  • Maps are two dimensional
  • The layout of a printed page is two dimensional
  • Computer generated images are two dimensional
  • Spreadsheets store data in rows and columns (two dimensional)

Basically anything that can be represented by a series of rows and columns

How can Python Store Two Dimensional Data

In python, this type of data is stored in lists.  A list in python can store any other type of data, even other lists.  So Two Dimensional data is effectively a list of other lists.

Each inner list represents an entire row of your two dimensional data 

For example, let’s say I had this set of data I wanted to store in python

ICS4U-2D-List-Data-Example
				
					myData = [ [99,42,74,83,100],[90,91,72,88,95],[88,61,74,89,96],[61,89,82,98,93],[93,73,75,78,99],[50,65,92,87,94],[43,98,78,56,99] ]
				
			

You might opt to write it like this for better readability

				
					myData = [  
            [99,42,74,83,100],
            [90,91,72,88,95],
	        [88,61,74,89,96],
	        [61,89,82,98,93],
	        [93,73,75,78,99],
	        [50,65,92,87,94],
	        [43,98,78,56,99]   
        ]
				
			

There is no requirement for the two dimensional data to be rectangular. 

Each row could have a different amount of columns.

There is also no requirement for the two dimensional data to have the same type of data

				
					myData = [
            ["Katie", 1, 3, 5, 7],
            ["Jennifer", 4.5, 2, 4],
            ["Marc", 0, -5]
        ]
				
			

Accessing Data in a 2D List

Just like using regular lists, you access the list data using index values.

  • If you specify only one index value, then python will return the entire inner list at that position
  • If you specify two index values, then you will get the data from the first indexes row at the second indexes column.

ICS4U Interactive Learning Activity - Grade 12 Computer Science

Let’s see what happens when you enter different index values

Enter the code below into the editor and see what it prints out, and if it is what you would expect

				
					myData = [
            ["Katie", 1, 3, 5, 7],
            ["Jennifer", 4.5, 2, 4],
            ["Marc", 0, -5]
        ]


print(myData[0])

print(myData[1])

print(myData[0][0])

print(myData[1][2])
				
			

Using Loops with 2D Lists

One big advantage of using a list is its ability to combine them with loops to access the data more efficiently

With a two dimensional list, you often use a nested loop with outer loop cycling through all the rows in your data, and the inner loop cycling through all the columns of the data

Example - Accessing / Printing All Values

				
					#Outer Loop Cycle Through each row of data
for i in range(0,len(myData)):

    #Inner Loop Cycle Through each column the specified row
    for j in range(0,len(myData[i])):

        #Print out data at the [i][j] location separated by spaces
        print(myData[i][j], end = " ")

    #Done a row, so go to new line to print the next
    print()
				
			

There is also a way to access this data using advanced for loops in python

				
					#The row variable represents an entire inner list of the bigger 2D list
for row in myData:

    #The value variable represents a piece of data in each inner list
    for value in row:

        #Print a data value, separated by spaces
        print(value,end = " ")

    #Done a row, so go to new line to print the next
    print()
				
			

If you just want a quick way to look at the values in your 2D list without making it “pretty” in your output window, you can just print the variable name

				
					print(myData)
				
			

Example - Finding the Sum of the Rows

This example will add up the values in each row of a 2D list

				
					myData = [ [99,42,74,83,100],
			[90,91,72,88,95],
			[88,61,74,89,96],
			[61,89,82,98,93],
			[93,73,75,78,99],
			[50,65,92,87,94],
			[43,98,78,56,99] ]

#Cycle through each row
for i in range(0,len(myData)):

	#Cycle through each value in each column and add them up
	rowTotal = 0
	for j in range(0,len(myData[i])):
		rowTotal = rowTotal + myData[i][j]

	print(rowTotal)
				
			

Example - Generating Random List Values

This example will generate a 2D list using random numbers

				
					import random

#The 2D list
myData = []

#Size of the two list
numRows = 5
numColumns = 3

#Outerloop controls the number of rows
for i in range(0,numRows):

    #Each row is its own list, start with a blank list
    row = []

    #Inner loop generates a random number and adds it as a colum to the rows
    for j in range(0,numColumns):
        number = random.randint(1,100)
        row.append(number)

    #A row is full so add it to the 2D list
    myData.append(row)

#Not a nicely formatted, print, but good for testing
print(myData)
				
			

Example - Keyboard Input of a List Values

The easiest way to get the input from the keyboard is similar to the last example.  Instead of generating the random number, you can just use an input statement, then input 1 value per line, hitting enter after each input.

				
					#The 2D list
myData = []

#Size of the two list
numRows = 5
numColumns = 3

#Outerloop controls the number of rows
for i in range(0,numRows):

    #Each row is its own list, start with a blank list
    row = []

    #Inner loop asks for the value from the keyboard, converts data type (if necessary)
    for j in range(0,numColumns):
        number = int(input("Enter a value: "))
        row.append(number)

    #A row is full so add it to the 2D list
    myData.append(row)

#Not a nicely formatted, print, but good for testing
print(myData)
				
			

Might be more efficient to be able to just enter an entire row at a time and make use of delimiters and the split function

				
					#The 2D list
myData = []

#Size of the two list
numRows = 5

for i in range(0,numRows):

    #Ask for the row of data separated by commas
    row = input("Enter the Entire Row: ").split(",")
    myData.append(row)

print(myData)
				
			

One thing you might notice from this is that your data in the 2D list would be all string values.  If you wanted numbers you would either have to convert at an appropriate time later in your code, or you could make use of some other python functions shown below.

				
					#The 2D list
myData = []

#Size of the two list
numRows = 5

for i in range(0,numRows):

    #Ask for the row of data separated by commas
    row = input("Enter the Entire Row: ").split(",")

    #Convert all the values in the split list into integers
    row = list(map(int,row))

    #Add to the 2D list
    myData.append(row)


print(myData)
				
			

ICS4U Coding Questions

Try to code the following questions using an IDE of your choice.  You will save those files on your computer for future reference. 

Each question has:

  • A video of your teacher live coding and explaining the solution
  • The final code used in the video.

Try your best to solve the problems yourself without looking at the solutions.

Make sure you test your programs with multiple different inputs to ensure it is functioning properly.

Treat these questions like Math homework (Do as many as you feel you need to do to feel comfortable with the material)

ICS4U Practice Question

Name Your File:  “ICS4UdiagonalSum.py” 

Take a randomly generated square 2D List (same # of rows and columns) and find the sum of both diagonals

				
					import random

#The 2D list
myData = []

#Size of the two list (Pick whatever you want)
size = 5

#Generating the random Values
for i in range(0,size):

    row = []
    for j in range(0,size):
        number = random.randint(0,9)
        row.append(number)

    myData.append(row)

#Print Out a nice output of the generated list
for i in range(0,size):

    for j in range(0,size):
        print(myData[i][j], end = " ")

    print()


#First Diagonal (Top Left to Bottom Right)
total = 0
for i in range(0,size):
   total = total + myData[i][i]
print("Top Left to Bottom Right Diagonal Sum is: ", total)

#Second Diagonal (Top Right to Bottom Left)
total = 0
for i in range(0,size):
    total = total + myData[i][size-i-1]
print("Top Right to Bottom Left Diagonal Sum is: ", total)
				
			

ICS4U Practice Question

Name Your File:  “ICS4UcountSymbols2D.py” 

The given code generates a 2D list of a random size, randomly with 4 symbols: *, -, $, @

Write some additional code that counts how many of each of the those symbols shows up in the list each time the program is run.

				
					import random

#The 2D list
myData = []

#Size of the two list
numRows = random.randint(3,7)
numColumns = random.randint(3,7)

#Generating the random List
symbols = ["*","-","$","@"]
for i in range(0,numRows):

    row = []
    for j in range(0,numColumns):
        symbol = random.choice(symbols)
        row.append(symbol)

    myData.append(row)

#Print Out a nice output of the generated list
print("The list: ")
for i in range(0,numRows):

    for j in range(0,numColumns):
        print(myData[i][j], end = " ")

    print()
				
			

				
					import random

#The 2D list
myData = []

#Size of the two list
numRows = random.randint(3,7)
numColumns = random.randint(3,7)

#Generating the random List
symbols = ["*","-","$","@"]
for i in range(0,numRows):

    row = []
    for j in range(0,numColumns):
        symbol = random.choice(symbols)
        row.append(symbol)

    myData.append(row)

#Print Out a nice output of the generated list
print("The list: ")
for i in range(0,numRows):

    for j in range(0,numColumns):
        print(myData[i][j], end = " ")

    print()

#Count how many of each symbol
count = [0,0,0,0]
for i in range(0,numRows):
    for j in range(0,numColumns):

        #Cycle through all the values in the symbol list and compare to current [i][j] value in the 2D list
        for k in range(0,len(symbols)):
            if myData[i][j] == symbols[k]:
                count[k] = count[k] + 1

print("\nThe count: ")
for i in range(0,len(symbols)):
    print(symbols[i],"=",count[i])
				
			

ICS4U Practice Question

Name Your File:  “ICS4Utranspose.py” 

Write a program that creates a new 2D list where the rows of the first 2D list become the columns of the new 2D list.  This is called the transpose of the 2D List.  Assume the list is a rectangle. (Each row has the same number of columns)

				
					#Simple Example to test
original = [
                [2,3,4],
                [7,8,9],
            ]

#Find transpose of rectangular 2D List
transpose = []
transposeRows = len(original[0]) # equals number of columns in original
transposeColumns = len(original) # equals number of rows in original

#To switch the rows and columns append the [j][i] value of the original to the [i][j] value in the new list
for i in range(0,transposeRows):

    row = []
    for j in range(0,transposeColumns):

        row.append(original[j][i])

    transpose.append(row)

#Print Transpose
for i in range(0,transposeRows):

    for j in range(0,transposeColumns):

        print(transpose[i][j],end = " ")

    print()
				
			

ICS4U Practice Question

Name Your File:  “ICS4UsumOfColumns.py” 

Write an algorithm that can find the sum of the columns in a 2D List. 

  • Start with writing the code for a rectangular list as that is much easier
  • Modify the code to handle a list that has rows with different length columns (this one is much harder)
				
					rectangularList =   [
                        [2,3,4],
                        [7,8,9],
                    ]

nonRectangularList =[
                        [2,3,4,5],
                        [7,9,5,6,9,3,2],
                        [2,5],
                        [3,4,5,6,9,10]
                    ]
				
			

				
					rectangularList =   [
                        [2,3,4],
                        [7,8,9],
                    ]

nonRectangularList =[
                        [2,3,4,5],
                        [7,9,5,6,9,3,2],
                        [2,5],
                        [3,4,5,6,9,10]
                    ]


#Sum of the columns in a rectangular list
sumRectangular = []
#Outer loop cycles through the number of columns needed
for i in range(0, len(rectangularList[0])):

    #Inner loop cycles through each row and adds the value
    colTotal = 0
    for j in range(0, len(rectangularList)):
        colTotal = colTotal + rectangularList[j][i]
    sumRectangular.append(colTotal)

print("The sum of the Rectangular List columns: ",sumRectangular)



#Sum of the columns in a non rectangular list
sumNonRectangular = []

#Find the all the column widths first
columnWidth=[]
for i in range(0, len(nonRectangularList)):
    columnWidth.append(len(nonRectangularList[i]))

#Outer loop cycles through the number of columns needed
for i in range(0,max(columnWidth)):

    #Inner Loop cycles through each row and adds the value
    colTotal = 0
    for j in range(0, len(nonRectangularList)):
        #Make sure there is a column value to add from
        if i < columnWidth[j]:
            colTotal = colTotal + nonRectangularList[j][i]
    sumNonRectangular.append(colTotal)

print("The sum of the Rectangular List columns: ",sumNonRectangular)

				
			

ICS4U Practice Question

Name Your File:  “ICS4UOneTwoSwitch.py” 

You are going to write a program that takes a 1D List of String Values (Any Length) and convert it to a 2D list with the user entering the number of columns to have in that new list.

The total number of entries in the 1D list might not match the space needed in the 2D list.  If this occurs fill in the empty 2D list spaces with empty string values.

  • For example, if there are 14 entries in the 1D list, and user wants the 2D list to have 3 columns, then it would need 5 rows, but that creates 15 spots spots in the 2D array, and only 14 values from the 1D array.  So that last spot would be filled in with a blank String.

				
					#The Lists
originalList = ["Hi", "Bye", "Out", "In", "Lost", "Won", "Train", "Bus", "Simmer", "Sizzle", "Bake", "Cook", "Dress", "Pants"]
newList = []

#Number of columns to tranform the list into
numColumnsNeeded = int(input("Enter the number of columns needed: "))

#Figure out the number of Rows needed for the 2D list based on the number of columns entered
if len(originalList) % numColumnsNeeded == 0:
    numRowsNeeded = len(originalList) // numColumnsNeeded
else:
    numRowsNeeded = len(originalList) // numColumnsNeeded + 1

#Location tracks what position of the 1D list is being added to the 2D list
location = 0

#Outer loop for the rows
for i in range(0,numRowsNeeded):
    row = []

    #inner loop for the columns
    for j in range(0,numColumnsNeeded):

        #Add the 1D list value unless they are all used up then add ""
        if location < len(originalList):
            row.append(originalList[location])
        else:
            row.append("")

        location = location + 1
    newList.append(row)

print(newList)

				
			

Return to ICS4U Main Page