Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python collections reference: selection costs and retained ownership

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

Python containers offer different ordering, membership and mutation contracts, so choosing one depends on the operation rather than only the stored value type.

Download Python source kit

Operation contract

The reference contrasts a list snapshot, set membership, dictionary defaults and a bounded deque. List copying separates the outer container, set membership answers whether an ID is present, and dictionary get reads a missing entry without creating it. Deque retains only the selected history length and intentionally discards older entries.

Failure and ownership boundary

This is a compact operation reference, not a universal complexity guarantee. Custom hashes, equality methods and nested aliases can change cost or behavior. A bounded history must not stand in for a ledger that must preserve every event. Python hash and equality: immutable dictionary keys, Python shallow and deep copies: preserve aliases deliberately and Python Counter and deque: counts, queues and bounded history provide the detailed contracts.

Working program

python
from collections import deque

receipt_ids = ["R-0041", "R-0042"]
outer_snapshot = receipt_ids.copy()
known = set(receipt_ids)
amounts = {"R-0041": 125}
history = deque(receipt_ids, maxlen=2)
history.append("R-0043")
print("member:", "R-0041" in known)
print("missing amount:", amounts.get("R-0099"))
print("key created:", "R-0099" in amounts)
print("retained history:", list(history))
receipt_ids.append("R-0044")
print("outer snapshot:", outer_snapshot)

Output

Output
member: True
missing amount: None
key created: False
retained history: ['R-0042', 'R-0043']
outer snapshot: ['R-0041', 'R-0042']

Costs and limits

List snapshot construction costs O(n) references. Set/dictionary membership has expected constant lookup work under suitable hashes. Deque endpoint operations avoid list-front shifting, while middle indexing/traversal has different costs.

Common Mistakes

  • An outer snapshot still shares mutable nested objects.
  • A bounded deque discards old history by design.

Connected lessons

Python hash and equality: immutable dictionary keys, Python shallow and deep copies: preserve aliases deliberately, Python Counter and deque: counts, queues and bounded history.

python
collections-reference
Storage details