Python Nested Lists

Python Nested Lists: Explanation & Examples

A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures.

1. Basic Nested List Creation

python

# A simple 2D list (matrix)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# A list containing mixed data types, including other lists
mixed_nested = [1, "hello", [10, 20], ["a", "b", "c"]]

2. Accessing Elements in Nested Lists

python

students = [
    ["Alice", 90, "Math"],
    ["Bob", 85, "Science"],
    ["Charlie", 78, "History"]
]

# Get first student's name
print(students[0][0])  # Output: "Alice"

# Get Bob's subject
print(students[1][2])  # Output: "Science"

# Get last student's grade
print(students[-1][1])  # Output: 78

3. Modifying Nested Lists

python

# Change Alice's grade to 95
students[0][1] = 95

# Add a new student
students.append(["David", 88, "Art"])

# Remove Bob's record
students.pop(1)

print(students)
# Output: [['Alice', 95, 'Math'], ['Charlie', 78, 'History'], ['David', 88, 'Art']]

4. Iterating Through Nested Lists

python

# Print all student names
for student in students:
    print(student[0])

# Output:
# Alice
# Charlie
# David

# Print all grades
for student in students:
    print(student[1])

# Output:
# 95
# 78
# 88

5. Flattening a Nested List

Convert a 2D list into a 1D list.

Method 1: Using List Comprehension

python

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Method 2: Using itertools.chain

python

from itertools import chain
flattened = list(chain.from_iterable(matrix))
print(flattened)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

6. Creating a Nested List with List Comprehension

python

# Create a 3x3 matrix filled with zeros
matrix = [[0 for _ in range(3)] for _ in range(3)]
print(matrix)
# Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

# Create a multiplication table
multiplication_table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
print(multiplication_table)
# Output: [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]

7. Deep Copy vs Shallow Copy in Nested Lists

python

import copy

original = [[1, 2], [3, 4]]

# Shallow copy (nested lists are still references)
shallow_copy = original.copy()
shallow_copy[0][0] = 99
print(original)  # Output: [[99, 2], [3, 4]] (modified!)

# Deep copy (completely independent)
deep_copy = copy.deepcopy(original)
deep_copy[0][0] = 100
print(original)  # Output: [[99, 2], [3, 4]] (unchanged)

8. Practical Use Case: Student Gradebook

python

gradebook = [
    ["Alice", [90, 85, 92]],
    ["Bob", [78, 80, 75]],
    ["Charlie", [88, 91, 89]]
]

# Calculate average grade for each student
for student in gradebook:
    name, grades = student
    average = sum(grades) / len(grades)
    print(f"{name}'s average: {average:.2f}")

# Output:
# Alice's average: 89.00
# Bob's average: 77.67
# Charlie's average: 89.33

Key Takeaways

✔ Nested lists are lists inside lists
✔ Useful for multi-dimensional data (matrices, tables)
✔ Access elements using double indexing (list[i][j])
✔ Shallow copy affects original, deep copy does not
✔ Flattening converts 2D → 1D

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *