Advanced Lists
Nested lists, list manipulation, slicing, copying, and performance tips.
Overview
Master advanced list operations.
Nested Lists
# 2D matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Access element
print(matrix[1][2]) # 6
# Iterate through matrix
for row in matrix:
for item in row:
print(item, end=" ")
print()
# Matrix transpose
transposed = list(zip(*matrix))
print(transposed) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
# 3D list
cube = [[[0 for _ in range(3)] for _ in range(3)] for _ in range(3)]
List Slicing
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Basic slicing
print(lst[2:5]) # [2, 3, 4]
print(lst[:4]) # [0, 1, 2, 3]
print(lst[6:]) # [6, 7, 8, 9]
print(lst[::2]) # [0, 2, 4, 6, 8] (every 2nd)
print(lst[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reverse)
# Advanced slicing
print(lst[1:8:2]) # [1, 3, 5, 7]
print(lst[8:1:-2]) # [8, 6, 4, 2]
# Slice assignment
lst[2:4] = [20, 30]
print(lst) # [0, 1, 20, 30, 4, 5, 6, 7, 8, 9]
# Insert with slice
lst[2:2] = [10, 11]
print(lst) # [0, 1, 10, 11, 20, 30, 4, 5, 6, 7, 8, 9]
List Copying
import copy
original = [1, 2, [3, 4]]
# Shallow copy (different methods)
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)
# Deep copy
copy4 = copy.deepcopy(original)
# Modify nested list
original[2][0] = 99
print(original) # [1, 2, [99, 4]]
print(copy1) # [1, 2, [99, 4]] (shallow - affected!)
print(copy4) # [1, 2, [3, 4]] (deep - independent)
List Performance
import time
# Bad: O(n) for each append
lst = []
for i in range(100000):
lst.append(i) # O(1) amortized
# Good: Pre-allocate
lst = [None] * 100000
for i in range(100000):
lst[i] = i # O(1)
# Membership test
large_list = list(range(1000000))
start = time.time()
999999 in large_list # O(n)
print(f"List: {time.time() - start:.4f}s")
large_set = set(range(1000000))
start = time.time()
999999 in large_set # O(1)
print(f"Set: {time.time() - start:.6f}s")
Practice
Implement a matrix multiplication function.