Python Practice › List Programs › Program 59

3 × 3 grid

EasyList Programs · 59 of 100

Write a Python program to create a 3 × 3 grid where every row is [4, 5, 6].

Advertisement
Output
[[99, 5, 6], [4, 5, 6], [4, 5, 6]]

Approach

  1. Build each row with a comprehension so the rows are separate lists.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment