B2.2.2
Construct programs that apply arrays and lists
A 1D list is a sequence of elements stored in a single row.
One-Dimensional Lists (1D)
A 1D list is a sequence of elements stored in a single row.
# Declaration
numbers: list[int] = [1, 2, 3, 4, 5]
# Indexing (0-based)
print(numbers[0]) # 1 — first element
print(numbers[-1]) # 5 — last element
# Slicing
print(numbers[1:4]) # [2, 3, 4]
# Common operations
numbers.append(6) # Add to end
numbers.insert(0, 0) # Insert at index
numbers.remove(3) # Remove first occurrence of 3
popped = numbers.pop() # Remove and return last element
numbers.sort() # Sort in place
numbers.reverse() # Reverse in place
len(numbers) # Length of list
Two-Dimensional Lists (2D)
A 2D list is a list of lists — rows and columns, like a table or matrix.
# Declaration — 3 rows, 4 columns
matrix: list[list[int]] = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
# Accessing elements
print(matrix[0][0]) # 1 — row 0, col 0
print(matrix[2][3]) # 12 — row 2, col 3
# Iterating — row by row
for row in matrix:
for item in row:
print(item, end=" ")
print() # Newline after each row
# Output:
# 1 2 3 4
# 5 6 7 8
# 9 10 11 12
# Iterating with indices
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(f"matrix[{i}][{j}] = {matrix[i][j]}")
Accessing a Specific Row or Column
# Get entire first row
first_row = matrix[0] # [1, 2, 3, 4]
# Get first element of each row (column 0)
col_0 = [row[0] for row in matrix] # [1, 5, 9]
# Get diagonal (square matrix only)
diagonal = [matrix[i][i] for i in range(len(matrix))] # [1, 6, 11]
Shallow and deep copies
A shallow copy creates a new outer list while keeping references to the same nested objects. Changing a nested mutable value through either list therefore affects both lists.
original = [[1, 2], [3, 4]]
shallow = original[:]
shallow[0][0] = 99
print(original) # [[99, 2], [3, 4]]
A deep copy recursively copies nested objects, so later changes do not affect the original structure.
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0][0] = 99
print(original) # [[1, 2], [3, 4]]