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!
1array_2d = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5]
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 to select each array in array_2d
; the other to go through the items in each array of array_2d
.
Think of it this way: when you loop through a regular ol’ array, you loop through each individual element, right?
1array = [1, 2, 3, 4, 5]
2for item in array:
3 print(array)
Now, if we let:
1a = [1, 2, 3]
2b = [4, 5, 6]
3c = [7, 8, 9]
and we also let:
1array_2d = [a, b, c]
then looping through a 2-dimensional array is no different.
At any given moment, our loop variable will hold a
, b
, or c
, as shown below:
1for array in array_2d:
2 print(array) # this will print the entirety of a, b, and c.
It is at this moment you require a second loop if you want to access each element in a
, b
, or c
.
1array_2d = [a, b, c]
2
3for array in array_2d: # loop through the 2-dimensional array
4 for item in array: # loop through each item in the currently selected array
5 print(item)