📊 Working with Nested Lists

Nested lists (or 2D arrays) are lists that contain other lists. They're commonly used to represent matrices, tables, and hierarchical data structures in Python.

# Basic nested list
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(f"Matrix: {matrix}")
print(f"First row: {matrix[0]}")
print(f"Element at (1,1): {matrix[1][1]}")

🎯 Accessing Nested Lists

Python provides intuitive ways to access and manipulate nested list elements.

Basic Examples

# Different ways to access nested lists
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Access rows
print(f"First row: {matrix[0]}")
print(f"Last row: {matrix[-1]}")

# Access elements
print(f"Top-left: {matrix[0][0]}")
print(f"Center: {matrix[1][1]}")
print(f"Bottom-right: {matrix[2][2]}")

# Get dimensions
rows = len(matrix)
cols = len(matrix[0])
print(f"Dimensions: {rows}x{cols}")

🔍 Manipulating Nested Lists

Python allows various operations on nested lists, from simple modifications to complex transformations.

# Manipulating nested lists
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Modify elements
matrix[0][0] = 10
print(f"Modified first element: {matrix}")

# Add new row
matrix.append([10, 11, 12])
print(f"Added new row: {matrix}")

# Transpose matrix
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(f"Transposed: {transposed}")

# Flatten matrix
flattened = [x for row in matrix for x in row]
print(f"Flattened: {flattened}")

🎯 Key Takeaways

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent