Menu

2D Arrays

Building a 2D array

A 2D array in Python is a list of lists, so you can create one with its starting values already in place. The outer list holds the rows, and each inner list holds the values for one row, one per column.

Writing the whole array at once

Write one outer pair of square brackets and put an inner list inside it for every row. The stock array below represents 3 shelves with 4 spaces on each shelf, and every space starts at 0:

stock = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
print(stock)

Output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

This is quick to read and quick to type, so it is the usual choice when you already know the values and the size of the array.

Building it row by row

When the starting values follow a pattern, or when the number of rows and columns is held in variables, build the array one row at a time:

  1. Create an empty outer list to hold the whole array.
  2. For each row, create a new inner list (empty at first).
  3. Append a starting value for each column to that inner list (here, four zeros).
  4. Append the finished inner list to the outer list.
rows = 3
columns = 4
stock = []
for shelf in range(rows):
    new_shelf = []
    for space in range(columns):
        new_shelf.append(0)
    stock.append(new_shelf)

print(stock)

Output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

The outer loop runs once per row. For each row, the inner loop adds four starting values to the new inner list, and then that finished row is appended to the outer list. After three passes the outer list holds three finished rows, and each row holds four starting values.

Every row needs its own list

The inner list must be created inside the loop. If you create one inner list before the loop and append it on every pass, the outer list ends up holding several references to the same list. You then have one row shown three times, not three rows: changing a value in the first row also changes the second and third, because there is really only one list being pointed at from three places. Creating a fresh inner list each time keeps the rows independent, so a change to one row leaves the others alone.

Practise this