Comprehensions, Nested Values, and Mutation
Build collections from existing data and reason about shared mutable objects.
python, comprehensions, nested structures, mutability, copyingFrom a collection to a result
A comprehension describes how to build a new collection from an iterable.
Read [expression for item in items if condition] as: visit each item, keep
those meeting the condition, and evaluate the expression for each kept item.
The if is optional. This creates a new list; it does not edit the input.
Python illustration
scores = [2, 5, 6]
doubled = [score * 2 for score in scores if score >= 5]
rows = [[1], [2]]
alias = rows
copy = rows.copy()
alias[0].append(9)
print(doubled)
print(rows)
print(copy)
print(copy is rows, copy[0] is rows[0])
Prepared output — not live execution:
[10, 12]
[[1, 9], [2]]
[[1, 9], [2]]
False True
rows and alias name one outer list. copy() creates a different outer
list, but its elements still refer to the same inner lists. The inner append
is therefore visible through both outer lists.
See the reasoning
Follow the example one step at a time
Follow the filter, then compare an alias with a shallow copy. This is a prepared teaching demonstration, not live code execution.
Start the comprehension
scores: [2, 5, 6] result: []
Visit the original scores in order; the result starts empty.
Other forms and boundaries
{word: len(word) for word in words} builds a dictionary; repeated equal
keys replace earlier values. {len(word) for word in words} builds a set
of distinct lengths. Nested comprehensions can represent nested loops, but
ordinary loops are often clearer when logic is complicated.
Lists, dictionaries and sets are mutable: their contents can change in place.
Strings, integers and tuples are immutable, though a tuple may reference a
mutable list. Rebinding a name is not the same as mutating its object.
Use copy.deepcopy when independent nested objects are genuinely needed;
it has its own cost and behaviour for shared and custom objects. A shallow
copy is enough when elements need not be changed independently.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
