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

  • Bank Account Class with Minimum Balance

    Challenge Summary: Bank Account Class with Minimum Balance Objective: Create a BankAccount class that automatically assigns account numbers and enforces a minimum balance rule. 1. Custom Exception Class python class MinimumBalanceError(Exception): “””Custom exception for minimum balance violation””” pass 2. BankAccount Class Requirements Properties: Methods: __init__(self, name, initial_balance) deposit(self, amount) withdraw(self, amount) show_details(self) 3. Key Rules: 4. Testing…

  • Inheritance in OOP Python: Rectangle & Cuboid Example

    Rectangle Inheritance in OOP Python: Rectangle & Cuboid Example Inheritance in object-oriented programming (OOP) allows a new class (the child class) to inherit properties and methods from an existing class (the parent class). This is a powerful concept for code reusability ♻️ and establishing a logical “is-a” relationship between classes. For instance, a Cuboid is…

  • Decorators in Python

    Decorators in Python A decorator is a function that modifies the behavior of another function without permanently modifying it. Decorators are a powerful tool that use closure functions. Basic Concept A decorator: Simple Example python def simple_decorator(func): def wrapper(): print(“Something is happening before the function is called.”) func() print(“Something is happening after the function is…

  • Create lists

    In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods: 1. Direct Initialization (Using Square Brackets []) The simplest way to create a list is by enclosing elements in square brackets []. Example: python empty_list = [] numbers = [1, 2, 3, 4] mixed_list = [1, “hello”, 3.14,…

  •  index(), count(), reverse(), sort()

    Python List Methods: index(), count(), reverse(), sort() Let’s explore these essential list methods with multiple examples for each. 1. index() Method Returns the index of the first occurrence of a value. Examples: python # Example 1: Basic usage fruits = [‘apple’, ‘banana’, ‘cherry’, ‘banana’] print(fruits.index(‘banana’)) # Output: 1 # Example 2: With start parameter print(fruits.index(‘banana’, 2)) # Output: 3 (starts searching…

  • List of Basic Regular Expression Patterns in Python

    Complete List of Basic Regular Expression Patterns in Python Character Classes Pattern Description Example [abc] Matches any one of the characters a, b, or c [aeiou] matches any vowel [^abc] Matches any character except a, b, or c [^0-9] matches non-digits [a-z] Matches any character in range a to z [a-z] matches lowercase letters [A-Z] Matches any character in range…

Leave a Reply

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