Relate Container Storage to Public Behavior
Core idea
In CPython lists use resizable storage for object references; dictionaries and sets use hash-based tables. Internal capacities and growth strategies are implementation details. Lists preserve order; dictionaries preserve insertion order by language guarantee, while sets provide no iteration-order guarantee. A container may hold references to shared mutable objects.
import sysa=[]; sizes=[]for n in range(40): a.append(n); sizes.append(sys.getsizeof(a))print(len(set(sizes))>1, len(set(sizes))<len(sizes))On the tested build shallow size changes in steps; no exact growth ratio is assumed.
Expected output:
True TrueSeparate ordering contracts
d={'b':1,'a':2}; d['b']=3print(list(d))print(sorted(set(d)))Updating an existing key does not move it; sorting creates a deterministic order for set values.
Expected output:
['b', 'a']['a', 'b']Common mistake
Never infer dict or set capacity from len, or depend on exact allocation increments. Hash collisions affect performance; timing claims require measurements.
Practice
Record shallow list sizes as elements are added and removed; explain why the resulting pattern is not a portable API.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
List dictionary and set storage
Check your understanding of list dictionary and set storage.
What is printed?
d={"z":1,"a":2};d["z"]=9print(list(d))What is printed?
x=[];a=[x,x];a[0].append(1)print(a)Which order is a language guarantee?
Is exact list growth a language guarantee?