Python Nested Lists
Table of Contents
In the last lesson, we learned about Python List Comprehensions. Now let’s put lists inside other lists and work with rows and columns.
Let’s Talk About Lists Inside Lists
We know what a list is. It is a collection of items.
numbers = [1, 2, 3, 4, 5]names = ["Alex", "Sam", "John"]But what if we want to store a list inside another list?
That is a nested list. A list that contains other lists as its items.
Think of it like a table. A table has rows and columns. Each row is a list. And the whole table is a list of rows.
That is a nested list.
How to Create a Nested List in Python
We just put lists inside a list.
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]That is a 3x3 matrix. Three rows. Three columns.
It is a list. And each item in that list is another list.
We can also create smaller ones.
pairs = [[1, 2], [3, 4], [5, 6]]Or mixed ones.
data = [["Alex", 25], ["Sam", 30], ["John", 22]]That is a list of name-age pairs.
Accessing Items in a Nested List
To access an item in a nested list, we use two indices.
- First index: which inner list we want
- Second index: which item in that inner list
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0])Output
[1, 2, 3]That gives us the first inner list.
print(matrix[0][1])Output
2That gives us the second item of the first inner list.
Let me show more.
print(matrix[1][2]) # 6print(matrix[2][0]) # 7print(matrix[-1][-1]) # 9Let’s remember: first index for the row, second index for the column.
Changing Items in a Nested List
We can change items the same way. Just use both indices.
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix[0][1] = 20print(matrix)Output
[[1, 20, 3], [4, 5, 6], [7, 8, 9]]We changed the item at row 0, column 1. It was 2. Now it is 20.
Looping Through a Nested List in Python
We can use nested loops to go through all items.
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix: for num in row: print(num, end=" ") print()Output
1 2 34 5 67 8 9The outer loop goes through each row. The inner loop goes through each item in that row.
We can also use index-based loops.
for i in range(len(matrix)): for j in range(len(matrix[i])): print(matrix[i][j], end=" ") print()Same output. But the first way is cleaner.
Python Nested Lists: A Real-Life Example — A Grade Book
Let’s say we have a list of students. Each student has a name and a list of scores.
students = [ ["Alex", [85, 90, 78]], ["Sam", [92, 88, 95]], ["John", [70, 65, 80]]]
for student in students: name = student[0] scores = student[1] average = sum(scores) / len(scores) print(f"{name}: Average = {average:.1f}")Output
Alex: Average = 84.3Sam: Average = 91.7John: Average = 71.7That is a natural use of nested lists. Each student is a list. And their scores are another list inside.
A Real-Life Example — A Game Board
Let’s create a tic-tac-toe board.
board = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
def print_board(): for row in board: print("|".join(row)) print("-" * 5)
print_board()Output
| |----- | |----- | |-----Then we can place marks.
board[1][1] = "X"board[0][0] = "O"print_board()Output
O| |----- |X|----- | |-----That is how we can use nested lists to represent a board.
Flattening a Nested List in Python
Sometimes we want to turn a nested list into a single list. That is called flattening.
We can use a list comprehension.
matrix = [[1, 2], [3, 4], [5, 6]]flattened = [num for row in matrix for num in row]print(flattened)Output
[1, 2, 3, 4, 5, 6]Or a loop.
flattened = []for row in matrix: for num in row: flattened.append(num)print(flattened)Both work. The comprehension is shorter.
Creating a Nested List in Python
Let’s be careful when creating nested lists with repetition.
matrix = [[0] * 3] * 3print(matrix)Output
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]Looks fine. But if we change one item, all rows change.
matrix[0][0] = 1print(matrix)Output
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]Why? Because [[0] * 3] * 3 creates three references to the same inner list. So changing one changes all.
To avoid this, we use a list comprehension.
matrix = [[0] * 3 for _ in range(3)]matrix[0][0] = 1print(matrix)Output
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]Now each row is a separate list. That is the safe way.
A Real-Life Example — Seating Chart
seats = [ ["A1", "A2", "A3"], ["B1", "B2", "B3"], ["C1", "C2", "C3"]]
for row in seats: print(" ".join(row))Output
A1 A2 A3B1 B2 B3C1 C2 C3That is a simple seating chart.
Common Mistakes with Python Nested Lists
Mistake 1: Using One Index Instead of Two
matrix = [[1, 2], [3, 4]]print(matrix[0]) # [1, 2]print(matrix[0][0]) # 1If we want a single item, we need both indices.
Mistake 2: Going Out of Range
matrix = [[1, 2], [3, 4]]print(matrix[2][0]) # Error!There is no row at index 2. Only 0 and 1.
Mistake 3: Using the Wrong Index for Rows and Columns
matrix = [[1, 2], [3, 4]]print(matrix[0][1]) # 2print(matrix[1][0]) # 3Let’s remember: first index is the row. Second is the column.
Mistake 4: Creating Shared References
matrix = [[0] * 3] * 3matrix[0][0] = 1print(matrix)Output
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]So what do we do? We use a comprehension.
matrix = [[0] * 3 for _ in range(3)]Next, we will learn about Sorting Python Lists and arrange list items in a chosen order.