top of page
< Back

2D Arrays

What is a 2D array?

  • A 2D array is a collection of items arranged in a grid of rows and columns. You can think of it like a chessboard or a spreadsheet, where each cell holds one value.

  • You access any cell directly using two indices:

array[row][column]

Why use a 2D array?

  • It lets you store related data in a neat rectangular layout.

  • You can jump to any position in constant time, without moving other elements.


How do you access data in a 2D array?

  • You can get a value from the array using the row and column index values

value = array[row][col]
  • Returns the value at the given row and column.

  • You can set a value from the array using the row and column index values

  • Stores a new value at that position.

array[row][col] = value


  • Use nested loops to visit every element in row-major order:

for i in range(num_rows): 
    for j in range(num_cols): 
        print(array[i][j])


  • There are many other things you can accomplish with a 2d array, such as performing a linear search on the data. See below for an example of how that works.


bottom of page