Nested Data Structures
Combine lists, tuples, and dicts to model complex real-world data — student records, inventories, API responses.
15 min•By Priygop Team•Updated 2026
Nested Structures
Nested Structures
# List of lists (2D grid)
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(grid[1][2]) # 6 (row 1, col 2)
# List of dictionaries (common pattern!)
students = [
{"name": "Alice", "age": 20, "grades": [85, 90, 78]},
{"name": "Bob", "age": 22, "grades": [92, 88, 95]},
{"name": "Charlie", "age": 21, "grades": [70, 75, 80]},
]
for student in students:
avg = sum(student["grades"]) / len(student["grades"])
print(f"{student['name']}: avg = {avg:.1f}")
# Dictionary of lists
inventory = {
"fruits": ["apple", "banana", "cherry"],
"vegetables": ["carrot", "potato", "tomato"],
"dairy": ["milk", "cheese", "yogurt"],
}
for category, items in inventory.items():
print(f"\n{category.upper()}: {', '.join(items)}")
# Nested list comprehension
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
for row in matrix:
print(row) # [1,2,3], [2,4,6], [3,6,9]Tip
Tip
List of dicts is the most common data pattern in Python — it models database rows, API responses, and CSV data. Master iterating and filtering them.
Diagram
Loading diagram…
List for mutable sequences, tuple for immutable data, set for unique items
Common Mistake
Warning
Accessing nested data without checking existence. Use .get() chains: data.get('users', {}).get('name', 'Unknown') to avoid KeyError.
Practice Task
Note
(1) Create a list of student dicts with grades. (2) Calculate average grade per student. (3) Find the student with highest average.