01
Collections
The costs of a mutable sequential collection, the guarantee immutability brings, key-value mapping and ordering behavior, set operations, specialized containers, and what slicing copies versus shares.
- 01 Lists A list holds not the items but the links to them; putting a thousand items in creates 1000 objects but binding the list to a second name creates 0, appending the same item five times creates 1, and only three of eight growth forms build a new container.
- 02 Tuples Three of six operations fail on a tuple with an exception, but the operation that mutates an inner item still passes on a tuple; immutability is one layer deep, and in exchange the container gains the capability to be a key, as seen in three of five candidates.
- 03 Dictionaries Searching for the same item among two hundred does 200 comparisons in a list but 1 in a set and a dict; asking for keys returns not a copy but a view, and it sees a key added afterward — going from 2 to 3, while a list snapshot stays at 2.
- 04 Sets Deduplicating three hundred items does 15050 comparisons scanned by hand, 200 handed to a set, and all three give the same hundred items; all six set operations create 0 new items, and four build a new container while two mutate the existing one.
- 05 Specialized Collections Writing the same grouping with setdefault creates 320 containers, with a defaultdict 100; on a thousand-item stream, all three spellings produce 1000 objects but held is 1000 against 5, and rotating builds three containers with a list against none with a deque.
- 06 Slicing All eight slice forms create 0 new items and return a new container; a nested list produces 4 items and both inner lists are shared in the slice copy — the outer container is new, the contents are old.