2-Dimensional Arrays

All explanations I’ve heard from teachers AND from the few textbooks I’ve read have such a convoluted explanation of this data structure.

To put it simply, a 2-Dimensional array is nothing more than a single array that contains multiple other arrays. That’s it!

2d_array = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

When you arrange it like this, you see the tabular structure everyone talks about.

The other thing to know is how to loop through such an array. You’ll need exactly 2 loops for this.

One loop will loop through the array that contains the other arrays as you would regularly.

array1 = [1, 2, 3, 4, 5]
for array in array1:
  print(array)

When you loop through this sort of array, you loop through each individual element, right?

If we let:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

Then looping through an array with these arrays is no different:

array2 = [a, b, c]
for array in array2:
  print(array)

At any given moment, our loop variable (array) will hold either a, b, or c.

This is when you require your second loop, to loop through the currently selected array.

array2 = [a, b, c]
for array in array2: #loop through array2
  for item in array: #loop through the currently selected array
    print(item)

When you look at a 2D array with such a definition, it becomes a lot easier to scale up to however many dimensions you need.

This article was written on 19/05/2024. If you have any thoughts, feel free to send me an email with them. Have a nice day!