Python Practice › List Programs › Program 59
3 × 3 grid
Write a Python program to create a 3 × 3 grid where every row is [4, 5, 6].
Output
[[99, 5, 6], [4, 5, 6], [4, 5, 6]]
Approach
- Build each row with a comprehension so the rows are separate lists.
Solution
grid = [[4, 5, 6] for _ in range(3)]grid[0][0] = 99print(grid)Output
[[99, 5, 6], [4, 5, 6], [4, 5, 6]]
Line by line
Line 2
Changing one row proves the rows are independent.
Watch out
[[4, 5, 6]] * 3 repeats the same list object three times, so changing one row would change all of them.
Learn the concept
New to this topic? Read the lesson, then come back.