3.2.6 - Two-dimensional arrays (Python)

3.2.6 - Two-dimensional arrays (Python)

A two-dimensional collection models a table or grid. You will use Python lists of rows, access a value with two indexes and traverse the grid to solve a small counting problem.

Rows, columns and indexes

A two-dimensional array needs two indexes because a value has both a row and a column position.

A classroom plan can record 0 for an empty seat and 1 for an occupied seat. A Python equivalent is a list containing one list per row:

Python
seats = [[1, 0, 1], [0, 1, 0]]
print(seats[1][0])

The outer index 1 chooses the second row, [0, 1, 0]; the inner index 0 chooses that row's first item, so the output is 0. Read the indexes in the stated row/column order, not as Cartesian x/y coordinates.

Row indexColumn 0Column 1Column 2
0101
1010

There are two rows and three columns: row indexes 0–1 and column indexes 0–2. len(seats) is 2 because it counts outer elements (rows); len(seats[0]) is 3 because it counts the first row's elements. To occupy row 1, column 0, assign 1 to that position.

Python
seats[1][0] = 1

One-dimensional arrays use one index; two-dimensional arrays use two. These are the dimensions required by this specification. The rectangular examples here use rows of equal length.

Traversing a two-dimensional array

Nested iteration can visit every cell by choosing each row and then each column within that row.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account