Nested for loops to access images#
We can access the color information of certain columns of images in a similar way. We still have the 3X4 image saved as a 2D list our_image
.
The RGB values of each pixel is as follows:
(0,0,0) (0,80,0) (0,160,0) (0,240,0)
(120,0,0) (120,80,0) (120,160,0) (120,240,0)
(240,0,0) (240,80,0) (240,160,0) (240,240,0)
Using tricks we’ve learned so far, we can output each column by copy/pasting code:
for column in range(4):
print(our_image[1][column])
for column in range(4):
print(our_image[2][column])
which leads to
(120,0,0)
(120,80,0)
(120,160,0)
(120,240,0)
(240,0,0)
(240,80,0)
(240,160,0)
(240,240,0)
as we wanted. However, nested for
loops can generate the same result with more concise code as follows:
for row in range(1,3):
for column in range(4):
print(our_image[row][column])
Here are the details of how the nested for
loops printed the desired result.
row
is1
at the initial iteration of the outerfor
loopcolumn
is0
at the initial iteration of the innerfor
loopour_image[1][0]
is printedcolumn
is1
at the next iteration of the innerfor
loopour_image[1][1]
is printedcolumn
is2
at the next iteration of the innerfor
loopour_image[1][2]
is printedcolumn
is3
at the next iteration of the innerfor
loopour_image[1][3]
is printed
row
is2
at the next iteration of the outerfor
loopcolumn
is0
at the initial iteration of the innerfor
loopour_image[2][0]
is printedcolumn
is1
at the next iteration of the innerfor
loopour_image[2][1]
is printedcolumn
is2
at the next iteration of the innerfor
loopour_image[2][2]
is printedcolumn
is3
at the next iteration of the innerfor
loopour_image[2][3]
is printed
Similarly, we can print the information of the entire image!
for row in range(3):
for column in range(4):
print(our_image[row][column])
Here is the output.
(0,0,0)
(0,80,0)
(0,160,0)
(0,240,0)
(120,0,0)
(120,80,0)
(120,160,0)
(120,240,0)
(240,0,0)
(240,80,0)
(240,160,0)
(240,240,0)
You can be assured that the correct information is printed according to the RGB table of the image above.