When dealing with 2D lists, it’s also possible to iterate over objects with a list comprehension.
grid = [
[10, 20, 30],
[40, 50, 60],
]
squared = [[i * i for i in row] for row in grid]
print(squared)
# [[100, 400, 900], [1600, 2500, 3600]]
Here the outer loop goes over the grid row-by-row. Then we iterate over each item in a row.
In case we don’t want to have a 2D list as a result, we can flatten out the grid by omitting the inner brackets and moving the for i in row out of the inner loop. We first iterate over the grid with for row in grid and then for i in row:
grid = [
[10, 20, 30],
[40, 50, 60],
]
squared = [i * i for row in grid for i in row]
print(squared)
# [100, 400, 900, 1600, 2500, 3600]
Challenge
Can you use list comprehension to print out all the coordinates of a chessboard?
The numbers go from 1 to 8, and the letters are A B C D E F G H. The numbering goes like A1 B1 C1 ... H1 the next line is A2 B2 C2 ... H2, etc. Print each line separately.