More on looping

5.37. More on looping#

So far, all the looping has been quite simple – iterating over a one dimensional series. This means we have used a single for statement. But it’s not uncommon to have (at least) a 2-dimensional array (e.g. numbers). How can we iterate over all elements in such a case?

In the following example, two_d is a list of lists.

two_d = [[0, 4, 1, 9, 5],
         [1, 4, 7, 1, 3]]

It has 2 “rows” and 5 “columns”. So rows is the first dimension, columns the second. First let’s recap some standard Python operations. We index the first row.

two_d[0]
[0, 4, 1, 9, 5]

The second row, first column.

two_d[1][0]
1

Note

We can index (or slice) a multi-dimensional data by extending the square bracket notation with each pair of square brackets referencing additional dimensions.

Knowing, in this case, that we have 2 rows and 5 columns we can generate all possible indices with nested for loops combined with the builtin range() function.

for i in range(2):
    for j in range(5):
        pass

In the above, for each step through the “outer most loop” (for i in ...) we execute the entire “inner most loop”. I’ll demonstrate this by just adding a print statement.

for i in range(2):
    for j in range(5):
        print(f"i={i}, j={j}")
i=0, j=0
i=0, j=1
i=0, j=2
i=0, j=3
i=0, j=4
i=1, j=0
i=1, j=1
i=1, j=2
i=1, j=3
i=1, j=4

These for loops have only generated series of integers. These are useful, in the context of two_d, in that we can use these to obtain the corresponding values using indexing, like so.

for i in range(2):
    for j in range(5):
        print(two_d[i][j])
0
4
1
9
5
1
4
7
1
3

We can also combine these loops with conditional statements so that we can selectively do operations only when we encounter a value that matches some condition. I’ll just display the row and column indices when we the value is 4.

for i in range(2):
    for j in range(5):
        if two_d[i][j] == 4:
            print(f"i={i}, j={j}")
i=0, j=1
i=1, j=1

5.38. Exercises#

  1. Consider the following two-dimensional list

    [[0, 4, 1],
     [1, 7]]
    

    The number of “columns” is different between the first and second rows. Write a nested for loop that prints the row index, column index and the value of every element in that list.

    It should produce output like:

    row=0 col=0 val=0
    row=0 col=1 val=4
    ...
    
  2. Construct a list of lists that contains different data types, some ints, some floats, some strings. Then using nested iteration, record the row and column coordinates (in separate lists) when the value is a string. For instance, if I used [[0, "data", 3.1]] and I would produce [0], [1].