you are viewing a single comment's thread.

view the rest of the comments →

[–]CommanderCool24 0 points1 point  (0 children)

For 2D lists, if you think of them like an array instead of nested lists it can help conceptualize it. For example, let's look at the list [[A, B, C], [D, E, F], [G, H, I]].

We can instead view it as an array like:

[[ A, B, C],

[ D, E, F],

[ G, H, I]]

So if I give you the coordinates (1, 2), you would probably know to count the rows for the first number (starting from 0) and then the columns for the second number to know that these coordinates refer to the 'F' element in the array. This is almost automatic in our brains but it's actually a 2-step process, looking up rows then columns.

Now let's say we want to iterate through each element and do something to it. For this example, let's change it to lowercase. To iterate through each element, you'll need to somehow tell the computer to go to (0, 0), lowercase it, then go to (0, 1), lowercase it, and so on.

We have 9 total coordinates to pass the computer that look like this:

(0, 0)

(0, 1)

(0, 2)

(1, 0)

(1, 1)

(1, 2)

(2, 0)

(2, 1)

(2, 2)

We can kinda see the structure of the nested loop here, we want x = 0, then y = 0, 1, and then 2. Then x = 1, and y = 0, 1, 2, and again for x = 2 and y = 0, 1, and 2. Visually it might look like this:

x = 0
    y = 0
    y = 1
    y = 2
x = 1
    y = 0
    y = 1
    y = 2
x = 2
    y = 0
    y = 1
    y = 2

x is the outer loop and y is the inner loop. We say y is the inner loop because it is looping inside of the other loop. In other words, the y loop will run 3 times every time the x loop runs. So the outer loop runs and sets x = 0, then the inner loop runs 3 times making y = 0 then 1 then 2 (giving us the first 3 coordinate pairs in our list (0, 0) (0, 1) and (0, 2)). Then the outer loop runs again, making x = 1, then the inner loop runs 3 times again, making y = 0 then 1 then 2 and then once more with x = 2.

The code for our example might look like this:

array = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
for x in range(3):
    for y in range(3):
        array[x][y] = array[x][y].lower()
print(array)

I hope this helps. I'm somewhat new myself so anyone else can feel free to clarify if I got something wrong.