2D Arrays
A two-dimensional (2D) array stores its elements in rows and columns, all held under a single identifier. Because the data has two dimensions, every element is found using two indexes: the row index first, then the column index.
Some data simply has two dimensions: a word search grid, a battleships board, or a stock list showing how many of each product each shop holds. Keeping it in one 2D array holds the whole table together, so you can work with a row, a column or the entire grid instead of juggling dozens of separate variables.
Every element in a 2D array holds the same data type: all numbers or all strings, because the array represents one kind of data. A 2D array of ticket prices can store the amounts, but it cannot also store the film titles, as those are text.
A row is one line across the array, found by the first index. A column is the set of elements in the same position in every row, found by the second index. Columns are not stored separately: you gather a column by keeping the second index the same and moving down through the rows.
In Python a 2D array is written as a list of lists. The outer list holds the rows, and each inner list is one complete row. Every inner list should contain the same number of elements, and that number is how many columns the array has.
car_park = [
["taken", "empty", "empty", "taken"],
["empty", "empty", "taken", "empty"],
["taken", "taken", "empty", "taken"]
]
print(car_park[1]) # the whole second row
print(car_park[2][3]) # one space: row 2, column 3Output:
['empty', 'empty', 'taken', 'empty']
taken
This car park has three rows of four spaces, so there are 3 × 4 = 12 elements in total. car_park[1] gives you the whole second row (a single inner list) and car_park[2][3] picks out one space, naming the row first and the column second. If one inner list had a different length, the array would no longer be a neat grid, so all rows are kept the same size.