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

  • Functions as Objects

    Functions as Objects and First-Class Functions in Python In Python, functions are first-class objects, which means they can be: 1. Functions as Objects In Python, everything is an object, including functions. When you define a function, you’re creating a function object. python def greet(name): return f”Hello, {name}!” # The function is an object with type ‘function’…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

  • pop(), remove(), clear(), and del 

    pop(), remove(), clear(), and del with 5 examples each, including slicing where applicable: 1. pop([index]) Removes and returns the item at the given index. If no index is given, it removes the last item. Examples: 2. remove(x) Removes the first occurrence of the specified value x. Raises ValueError if not found. Examples: 3. clear() Removes all elements from the list, making it empty. Examples: 4. del Statement Deletes elements by index or slice (not a method, but a…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

Leave a Reply

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