Beginner Chapter 44 · 25 min read · Module 4: Python Data Structures
Nested Lists
- After this chapter you can create a nested list such as a grid or table.
- You can read and change an inner item with `grid[row][col]`.
- You can loop over rows and columns with nested `for` loops.
- You can explain why `[[0] * 3] * 3` is a trap and how to build rows safely.
- You can copy a nested list with `copy.deepcopy`.
A list can hold any kind of value, and that includes other lists. A list that contains lists is called a nested list. It is the simplest way to store a table, a game board, a seating plan or a small picture made of pixels.
Think of a spreadsheet. It has rows, and each row has cells. In Python you can write that as a list of rows, where every row is itself a list of cells. To find one cell you give two numbers: the row index and then the column index.
This chapter shows how to build nested lists, how to read and change them, how to loop over them, and how to copy them correctly. It also explains the most famous bug with nested lists, where several rows secretly turn out to be one row.
Creating a nested list
You write a nested list by putting lists inside the outer square brackets. Each inner list is one row. The rows do not have to be the same length, but for tables and grids they usually are.
Nested lists can go deeper than two levels. A list of tables is a three level list and needs three indexes, such as data[2][0][1]. In practice most programs stay with two levels, because more levels become hard to read. If your data has names for its parts, a list of dictionaries or a list of tuples is often clearer than a grid of plain numbers.
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(grid[0])
print(grid[1][2])
print(grid[-1][0])
print(len(grid), len(grid[0]))The expression grid[1] gives the whole second row, which is the list [4, 5, 6]. Then [2] picks the item at index 2 of that row. So grid[1][2] is 6. Read it from left to right: first choose the row, then choose the column. The length of grid is the number of rows, and the length of one row is the number of columns.
Changing items and rows
Lists can be changed, so you can assign to a cell with grid[row][col] = value. You can also replace a whole row, or add a new row with append. Methods such as append and remove work on the outer list or on any inner list, depending on which one you call them on.
board = [['.', '.', '.'], ['.', '.', '.']]
board[0][1] = 'X'
board[1][2] = 'O'
board.append(['#', '#', '#'])
board[1].insert(0, '>')
for row in board:
print(' '.join(row))Looping over a nested list
To visit every item you use a loop inside a loop. The outer loop picks each row. The inner loop picks each item of that row. If you need the index numbers as well, use range(len(...)) or enumerate.
scores = [[80, 90], [70, 60, 50], [100]]
for row in scores:
total = 0
for value in row:
total += value
print(row, total)
flat = [v for row in scores for v in row]
print(flat)
for r, row in enumerate(scores):
for c, value in enumerate(row):
if value == 60:
print('found 60 at', r, c)The shared-row trap
Beginners often write grid = [[0] * 3] * 3 to make a 3 by 3 grid. This looks fine, but the outer * 3 repeats the same inner list three times. All three rows are one object. When you change one row, all rows seem to change. The safe way is to build each row separately, for example with a list comprehension: [[0] * 3 for _ in range(3)].
bad = [[0] * 3] * 3
bad[0][0] = 5
print(bad)
print(bad[0] is bad[1])
good = [[0] * 3 for _ in range(3)]
good[0][0] = 5
print(good)
print(good[0] is good[1])[0] * 3 is fine, because numbers cannot be changed. The problem is only with the outer repeat, because it repeats a reference to a list that can be changed.Copying nested lists
A shallow copy such as grid[:] or grid.copy() makes a new outer list, but the rows are still shared. To copy everything, use copy.deepcopy from the standard library. It copies the rows and anything inside them.
import copy
m = [[1, 2], [3, 4]]
shallow = m.copy()
deep = copy.deepcopy(m)
m[0][0] = 99
print(shallow)
print(deep)
print(m)A common job is to swap rows and columns, called transposing. Python can do it in one line with zip(*grid), which pairs up the first items of every row, then the second items, and so on. The result is a group of tuples, so wrap it in list() if you need a list.
Ragged lists and safe access
Not every nested list is a neat rectangle. A list such as [[1], [2, 3], [4, 5, 6]] is called ragged, because the rows have different lengths. With ragged data you must not assume that every row has a column 2. Loop over each row with its own length, or check len(row) before you use an index. The nested for value in row style is safe for both regular and ragged data because it never uses a fixed column number.
When you print a nested list directly, Python shows the brackets of every level. That is fine for debugging, but for a nicer table you can print one row per line, or join the items of each row with spaces or commas. Good output habits make mistakes in your grid much easier to see.
Python syntax
grid = [[1, 2], [3, 4]]grid[row][col]grid[row][col] = value[[0] * cols for _ in range(rows)]import copy; copy.deepcopy(grid)Real-world applications
- Game boards such as tic-tac-toe or chess.
- Tables of marks: one row per student.
- Images stored as rows of pixel values.
- Matrices in maths and data science.
Common mistakes
[[0] * 3] * 3 and then seeing all rows change together.Fix: Create each row on its own:
[[0] * 3 for _ in range(3)].grid[1, 2] instead of grid[1][2].Fix: Plain lists need one pair of brackets per level. The comma form is for NumPy arrays.
grid.copy() copies the rows too.Fix: It is shallow. Use
copy.deepcopy(grid) when the rows must be independent.grid[col][row] raises IndexError or gives the wrong cell.Fix: Always write row first, then column. Say it out loud: grid[row][col].
Important tips
- Use names like
rowandcolin loops instead ofiandjwhen you can. - Print the whole grid row by row while testing; it is easier to read.
- Use
[v for row in grid for v in row]to flatten one level.
Key points summary
- A nested list is a list of lists; use two indexes to reach an item.
- len(grid) counts rows and len(grid[0]) counts columns of a regular grid.
- Nested loops visit each cell.
- [[0] * n] * m repeats one row; use a comprehension instead.
- copy.deepcopy makes a fully independent copy.
Exam and interview points
- grid[r][c] means row r, column c.
- The shared-row trap with list repetition is a classic question.
- Shallow copies share inner objects.
- zip(*grid) transposes a grid.
Quick revision
- List of lists = table.
- Row first, then column.
- Loop in a loop for all cells.
- Do not use [[0]*3]*3.
- deepcopy for independent copies.
Frequently asked questions
How do I get the number of columns?
Take the length of any row, for example len(grid[0]), if all rows have the same length.
Can the inner lists have different lengths?
Yes. Python does not force equal lengths. These are called ragged lists, and you must be careful with indexes.
Why did all my rows change at once?
The rows are the same list object, usually from `[row] * n`. Build separate lists with a comprehension.
How do I flatten a nested list?
For one level, use a comprehension: [v for row in grid for v in row].
What is the difference between shallow and deep copy?
A shallow copy makes a new outer list but shares the inner lists. A deep copy also copies the inner lists.
Practise this chapter
23 practice questions Take the chapter quiz