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
gridrow-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 rowout of the inner loop. We first iterate over the grid with
for row in gridand 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]
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 ... H1the next line is
A2 B2 C2 ... H2, etc. Print each line separately.
Output A1 B1 C1 D1 E1 F1 G1 H1 A2 B2 C2 D2 E2 F2 G2 H2 A3 B3 C3 D3 E3 F3 G3 H3 A4 B4 C4 D4 E4 F4 G4 H4 A5 B5 C5 D5 E5 F5 G5 H5 A6 B6 C6 D6 E6 F6 G6 H6 A7 B7 C7 D7 E7 F7 G7 H7 A8 B8 C8 D8 E8 F8 G8 H8
You can use a single-line condition to determine if you’re printing a newline as the
endparameter of a