top of page
top

Python 8b - 2D Lists

noun-list-1242568-FFFFFF.png

Creating a List with Multiple Dimensions

Lists can be given another dimension to hold data that is related to each other.

​

A scenario: Three students have taken two Chemistry tests, and their teacher has recorded the results in a 2-dimensional array (note that Python does not use arrays but uses lists instead):

py138.png

To create this in Python:

py139.png

Printing a 2D List

To print the whole list, use a for loop to cycle through each record.

​

I have altered the normal i variable to be 'record', so it is more descriptive:

Use the index number to print a specific record.

 

Look at the table above and remember that Python starts counting at 0 so Edward is record 0, Bella 1 and Jacob 2:

py140.png
py142.png
py141.png
py143.png

To print a specific data value, you need to define the record number and then the data index.

​

When using 2D lists, the first value is the row, and the second value is the column.

 

Use the table at the very top to help you visualise this:

py144.png
py145.png

Practice Task 1

Use the introduction at the top to help you create a 2D list with three friends in the first column, their age in the second column and their favourite colour in the third column.

​

Print the whole list.

​

Then print just the second person's information.

Example solution:

py146.PNG

Searching Through a 2D List

To search through a multi-dimensional list then you need to search through each record and then each data element for a specific value:

py147.png
py148.png

Practice Task 2

Use the 2D list that you created in the first practice task.

​

Ask the user to enter a name.

​

Search through the list and print the record of that person's name.

Example solution:

py149.PNG
bottom of page