Lists, Dictionaries, Sets and Tuples
What is it?
Python's built-in collection types are the architectural scaffolding of all data engineering and machine learning workflows:
- List (
[]): A mutable, dynamic array of object references supporting index-based access, slicing, and dynamic resizing. - Tuple (
()): An immutable, fixed-length sequence ideal for static records, multidimensional coordinate pairs, and tensor shapes. - Dictionary (
{}): An associative mapping of unique, hashable keys to arbitrary values, implemented as a compact, cache-friendly hash table with average-case lookup. - Set (
set()): An unordered collection of unique, hashable elements providing high-performance mathematical set operations (union, intersection, symmetric difference) in time.
Algorithmic Complexity Comparison
Why we need it
In machine learning pipelines:
- Choosing the wrong collection ruins performance: Checking
if token in token_listinside a loop over a 100,000-word dataset takes minutes (), while converting to asetcompletes in milliseconds (). - Silent data corruption via shared references: Modifying a nested list or weight dictionary without understanding shallow vs deep copies will silently mutate training baselines.
- Tensor dimension safety: PyTorch and TensorFlow use tuples (
(batch_size, channels, height, width)) specifically because immutability guarantees dimensions cannot be accidentally mutated during forward computation. - Efficient Feature Mapping: Dictionaries and
collections.defaultdictform the backbone of tokenizers, categorical encoders, and vocabulary frequency analyzers in Natural Language Processing.
Explained in detail
1. Lists: CPython Memory Layout & Dynamic Resizing
In CPython, a Python list is not a linked list and not a raw C array of values. It is a contiguous dynamic array of pointers to Python objects:
[ Python List Object ]
├── size: 3
├── allocated: 4 (over-allocated capacity)
└── ob_item ───► [ Pointer 0 ] ───► Integer Object (10)
[ Pointer 1 ] ───► String Object ("loss")
[ Pointer 2 ] ───► Float Object (0.42)
[ Pointer 3 ] ───► (Unused capacity)Amortized Appending
When a list exceeds its current capacity, CPython allocates a larger contiguous memory buffer according to a geometric growth pattern:
Because reallocations happen exponentially less frequently as the list grows, appending is amortized. However, inserting or deleting from the beginning (list.insert(0, val)) forces every pointer in the array to shift right, costing time.
losses = []
for epoch in range(100):
losses.append(0.5 / (epoch + 1)) # O(1) amortized append2. Slicing Mechanics & Shallow Copying
Python slicing syntax follows sequence[start:stop:step]:
start: Inclusive starting index (defaults to0).stop: Exclusive ending index (defaults tolen(seq)).step: Stride amount (can be negative for reverse traversal).
data = [10, 20, 30, 40, 50, 60]
print(data[1:4]) # [20, 30, 40]
print(data[::2]) # [10, 30, 50] (every 2nd element)
print(data[::-1]) # [60, 50, 40, 30, 20, 10] (reversed copy)Slicing a List Creates a Shallow Copy: Slicing sub = data[1:4] allocates a new list of pointers, but the objects pointed to are not duplicated! For nested structures, modifying an inner list inside a slice mutates the original list.
Shallow Copy vs Deep Copy
import copy
original = [[1, 2], [3, 4]]
# Shallow copy: outer list is new, inner lists are shared pointers
shallow = original.copy() # or original[:]
shallow[0].append(99)
print(original) # [[1, 2, 99], [3, 4]] — CORRUPTED!
# Deep copy: recursively copies every nested object
deep = copy.deepcopy(original)
deep[0].append(100)
print(original) # [[1, 2, 99], [3, 4]] — UNTOUCHED!3. Tuples: Immutability & Structural Records
A tuple cannot be altered after construction. This property makes tuples:
- Memory-efficient: Tuples do not over-allocate extra buffer slots like lists.
- Thread-safe: Read-only access prevents race conditions during multithreaded data loading.
- Hashable: A tuple containing only hashable elements can be used as a dictionary key or set element.
# Fixed grid coordinates as dictionary keys
heat_map = {
(0, 0): 0.12,
(0, 1): 0.85,
(1, 0): 0.44,
}
print(heat_map[(0, 1)]) # 0.85Typed NamedTuples (typing.NamedTuple)
For clean, self-documenting records without the overhead of full classes:
from typing import NamedTuple
class BatchRecord(NamedTuple):
batch_id: int
loss: float
accuracy: float
batch = BatchRecord(batch_id=42, loss=0.28, accuracy=0.94)
print(batch.batch_id, batch.accuracy) # Access by name or index batch[0]4. Dictionaries: Hash Tables & Modern Compact Layout
Since Python 3.6+, CPython uses a compact hash table design that reduces memory footprint by up to 25% and guarantees insertion order preservation:
# Conceptual Compact Dict Layout:
indices: [None, 0, None, 1, None, None, 2, None] # Sparse hash table
entries: [
{"hash": 1234, "key": "lr", "val": 0.01}, # Dense array
{"hash": 5678, "key": "epoch", "val": 50},
{"hash": 9012, "key": "decay", "val": 1e-4}
]The Hash Function & Key Requirements
To place an item in a dictionary, Python calculates hash(key). Keys must be hashable:
- Immutable types (
int,float,str,tuple,frozenset) implement__hash__()and are valid keys. - Mutable types (
list,dict,set) do not implement__hash__()and raiseTypeError: unhashable type.
# Safe dictionary access patterns
metrics = {"val_loss": 0.35, "train_loss": 0.22}
# 1. get() with default fallback
accuracy = metrics.get("accuracy", 0.0)
# 2. setdefault() initializes missing keys safely
token_counts = {}
for word in ["loss", "epoch", "loss"]:
token_counts.setdefault(word, 0)
token_counts[word] += 15. Sets & Mathematical Set Algebra
Python sets are unordered collections of unique hashable elements. They excel at vocabulary extraction, categorical deduplication, and set operations:
train_classes = {"cat", "dog", "bird", "horse"}
val_classes = {"dog", "elephant", "cat"}
# Set Theory Operators:
print(train_classes & val_classes) # Intersection: {'cat', 'dog'}
print(train_classes | val_classes) # Union: all classes
print(train_classes - val_classes) # Difference: {'bird', 'horse'}
print(train_classes ^ val_classes) # Symmetric Difference: unique to eitherfrozenset: An immutable variant of set. Because it is immutable and hashable, you can store a frozenset inside another set or use it as a dictionary key!
6. Specialized ML Containers (collections Module)
Python's standard library provides high-performance specialized containers:
from collections import defaultdict, Counter, deque
# 1. defaultdict: Never raises KeyError
adjacency = defaultdict(list)
adjacency["node_0"].append("node_1") # Initializes empty list automatically!
# 2. Counter: Frequency analysis for NLP tokenizers
corpus = ["gradient", "descent", "stochastic", "gradient", "descent", "gradient"]
vocab_counter = Counter(corpus)
print(vocab_counter.most_common(2)) # [('gradient', 3), ('descent', 2)]
# 3. deque: Double-ended queue with O(1) appends and pops on BOTH ends
# Essential for sliding window metrics and replay buffers in Reinforcement Learning
replay_buffer = deque(maxlen=1000)
replay_buffer.append({"state": 1, "reward": 5.0})Quiz
🧩
Ready to test yourself?
4 questions · explanations shown after
Teach & Solidify
Teach This: Lists, Dictionaries, Sets and Tuples
Core Intuition
Lists are dynamic arrays of pointers; tuples provide immutable tensor shapes; dictionaries are compact O(1) hash maps; sets accelerate vocabulary lookups from O(n) to O(1).
Key Concepts to Explain
- 1Never check membership inside loops using lists: converting a list to a `set` drops query time from O(n) to O(1).
- 2Beware of shallow copies: `list.copy()` or slicing `[:]` duplicates only top-level pointers. Use `copy.deepcopy()` for nested weights or parameter dicts.
- 3Use `collections.defaultdict` and `Counter` to eliminate boilerplate `KeyError` checks in NLP tokenizers.
- 4Tuples and `NamedTuples` ensure that multi-dimensional tensor shapes remain immutable and tamper-proof throughout forward passes.
⚠️ What Most Students Get Confused About
Creating 2D matrices using `[[0] * cols] * rows`. This repeats the same list reference across all rows! Always construct 2D lists via list comprehension: `[[0] * cols for _ in range(rows)]`.
Explain Lists, Dictionaries, Sets and Tuples in your own words
Imagine you are explaining this idea to a friend or classmate with no math background. Writing it out forces your brain to bridge gaps in your intuition.
Resources & GitHub
Resources & Study Materials
Deepen your understanding with author-prepared study notes, derivation proofs, and curated educational lectures.
In-depth guide by Anthony Shaw on dynamic array growth, hash table layout, and memory allocation in CPython.
Official guide to high-performance containers: Counter, defaultdict, deque, and NamedTuple.
Hands-on Jupyter notebook covering slicing tricks, hash collision benchmarks, and deep copy demos.
Mastered this concept?
Tick this box when you feel confident explaining it.
Topic Resources
Was this clear?