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

  • Generalization vs. Specialization

    Object-Oriented Programming: Generalization vs. Specialization Introduction Inheritance in OOP serves two primary purposes: Let’s explore these concepts with clear examples. 1. Specialization (Extending Functionality) Specialization involves creating a new class that inherits all features from a parent class and then adds new, specific features. The core idea is reusability—you build upon what already exists. Key Principle: Child Class =…

  • date time modules class55

    In Python, the primary modules for handling dates and times are: 🕰️ Key Built-in Modules 1. datetime This is the most essential module. It provides classes for manipulating dates and times in both simple and complex ways. Class Description Example Usage date A date (year, month, day). date.today() time A time (hour, minute, second, microsecond,…

  • 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…

  •  List operators,List Traversals

    In Python, lists are ordered, mutable collections that support various operations. Here are the key list operators along with four basic examples: List Operators in Python 4 Basic Examples 1. Concatenation (+) Combines two lists into one. python list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 print(combined) # Output: [1, 2, 3,…

Leave a Reply

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