Nested Loops¶
For some complex tasks, it is necessary to include loops inside of other loops. This is called a nested loop. The simplest case of a nested loops is when we have one loop that itself contains another loop. In this case, we call the first loop that Python encounters the outer loop, and the loop inside of that is called the inner loop. Each time the outer loop runs, the entire inner loop will process, running through all of it’s possible iterations.
To get an introduction to how nested loops work, consider the following example.
for i in range(0, 6):
for j in range(0, 3):
print("i is equal to " + str(i) + "; j is equal to " + str(j))
print()
i is equal to 0; j is equal to 0
i is equal to 0; j is equal to 1
i is equal to 0; j is equal to 2
i is equal to 1; j is equal to 0
i is equal to 1; j is equal to 1
i is equal to 1; j is equal to 2
i is equal to 2; j is equal to 0
i is equal to 2; j is equal to 1
i is equal to 2; j is equal to 2
i is equal to 3; j is equal to 0
i is equal to 3; j is equal to 1
i is equal to 3; j is equal to 2
i is equal to 4; j is equal to 0
i is equal to 4; j is equal to 1
i is equal to 4; j is equal to 2
i is equal to 5; j is equal to 0
i is equal to 5; j is equal to 1
i is equal to 5; j is equal to 2
Example: Matrix Addition¶
The following cell contains a list of lists, named A
. This list is intended to represent a 3x5 matrix. Each of the three lists inside A
represents a single row with 5 elements.
A = [ [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25] ]
The cell below prints the rows of A
one at a time. This output will more closely resemble a matrix.
for row in A:
print(row)
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]
[21, 22, 23, 24, 25]
Assume that we wish to create a new list called ASquare
. This list should also represent a 3x5 matrix, and each element of ASquare
should be the square of the corresponding element of A
. This will require two loops. The first loop will loop over the rows of A
. The second loop will loop over the elements of a given row.
ASquare = []
for i in range(0,len(A)):
tempRow = []
for j in range(0,len(A[i])):
tempRow.append(A[i][j] ** 2)
ASquare.append(tempRow)
Notice that we build up each row in ASquare
one element at a time, and when we are finished with a row, we add that to ASquare
. We will now print the rows of ASquare
.
for row in ASquare:
print(row)
[121, 144, 169, 196, 225]
[256, 289, 324, 361, 400]
[441, 484, 529, 576, 625]