Sub topic 3
Building Lists with Comprehensions
Assume you know variables, for loops, if statements, functions, and basic Python types. This chapter focuses on list comprehensions, copying, nested lists, and operation costs.
Building lists with comprehensions
A list comprehension builds a new list from an iterable, often more clearly than a loop:
squares = [n * n for n in range(6) if n % 2 == 0]
print(squares) # [0, 4, 16]Read this as: “for each n, include n * n if n is even.” Use a regular loop when the logic has several steps or side effects.
Aliasing and copying
Assignment creates an alias. Both names refer to the same list. copy() creates a shallow copy, which duplicates the outer list but not nested objects. deepcopy() recursively copies nested objects.
from copy import deepcopy
original = [[1, 2], [3, 4]]
alias = original
shallow = original.copy()
deep = deepcopy(original)
original[0][0] = 9
print(alias[0][0]) # 9
print(shallow[0][0]) # 9
print(deep[0][0]) # 1Nested lists
A nested list contains other lists. Avoid multiplying an inner list, because every row then refers to the same object:
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]]Common mistakes
- Do not modify a list while iterating over it. Build a filtered list instead.
- Do not expect methods such as
sort()orappend()to return the changed list. They returnNone. - Do not use a comprehension only for side effects. Use a loop for actions such as printing or writing files.
Operation costs
Indexing and appending usually take constant time, written as O(1). Searching, removing by value, and inserting near the front take O(n), where n is the list length. Sorting takes O(n log n).
Stacks and queues
A list works well as a stack:
stack = []
stack.append("task")
stack.append("email")
print(stack.pop()) # emailFor a queue, use collections.deque. Removing the first list item with pop(0) shifts every remaining item.
from collections import deque
queue = deque(["A", "B"])
queue.append("C")
print(queue.popleft()) # AExercise
Which expression creates independent rows in a two-row grid?
Show answer
[[0] * 3 for _ in range(2)], because the comprehension creates a new inner list each time.