Facebook Pixel
🌙 Eid Mega SaleLimited Time OfferGet Python Bootcamp FREE withData ScienceandData AnalyticsCourses

⚠️ This bonus won't be available after the sale

Nested Lists

Nested Lists allow us to store lists inside another list. These are useful when we want to store structured or table-like data.

What are Nested Lists?

A nested list simply means a list that contains other lists as items.

# Nested List Example
students = [
    ["Harry", 20],
    ["Sarah", 22],
    ["Bruno", 21]
]
 
print(students)

Output:

[['Harry', 20], ['Sarah', 22], ['Bruno', 21]]

Each inner list represents a student's name and age.

Accessing Items in Nested Lists

To access elements inside nested lists, we use multiple indexes:

  • First index → selects the inner list
  • Second index → selects the item inside that inner list
# Accessing elements inside nested lists
students = [
    ["Harry", 20],
    ["Sarah", 22],
    ["Bruno", 21]
]
 
print(students[0][0])     # First student's name
print(students[1][1])     # Second student's age

Output:

Harry
22

Modifying Items in Nested Lists

We can change values inside nested lists using indexing.

# Modifying nested list items
students = [
    ["Harry", 20],
    ["Sarah", 22],
    ["Bruno", 21]
]
 
students[0][1] = 25       # Updating Harry's age
 
print(students)

Output:

[['Harry', 25], ['Sarah', 22], ['Bruno', 21]]

Iterating Through Nested Lists

1. Looping through each inner list

# Looping through nested lists
students = [
    ["Harry", 20],
    ["Sarah", 22],
    ["Bruno", 21]
]
 
for student in students:
    print(student)

Output:

['Harry', 20]
['Sarah', 22]
['Bruno', 21]

2. Looping through each value inside inner lists

# Looping through values inside nested lists
students = [
    ["Harry", 20],
    ["Sarah", 22],
    ["Bruno", 21]
]
 
for student in students:
    for value in student:
        print(value)

Output:

Harry
20
Sarah
22
Bruno
21

Nested Lists as Matrices (2D Lists)

Nested lists are useful when representing 2D data such as matrices.

# Matrix representation using nested lists
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
 
print(matrix[1][2])       # Row 1, Column 2

Output:

6