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

  • What is list

    In Python, a list is a built-in data structure that represents an ordered, mutable (changeable), and heterogeneous (can contain different data types) collection of elements. Lists are one of the most commonly used data structures in Python due to their flexibility and dynamic nature. Definition of a List in Python: Example: python my_list = [1, “hello”, 3.14,…

  • Why Python is So Popular: Key Reasons Behind Its Global Fame

    Python’s fame and widespread adoption across various sectors can be attributed to its unique combination of simplicity, versatility, and a robust ecosystem. Here are the key reasons why Python is so popular and widely used in different industries: 1. Easy to Learn and Use 2. Versatility Python supports multiple programming paradigms, including: This versatility allows…

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • String Alignment and Padding in Python

    String Alignment and Padding in Python In Python, you can align and pad strings to make them visually consistent in output. The main methods used for this are: 1. str.ljust(width, fillchar) Left-aligns the string and fills remaining space with a specified character (default: space). Syntax: python string.ljust(width, fillchar=’ ‘) Example: python text = “Python” print(text.ljust(10)) #…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

Leave a Reply

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