MML204

Lists, Dictionaries, Sets and Tuples

⏱7 min read👁️Eye-Care Reading Mode

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 O(1)O(1) average-case lookup.
  • Set (set()): An unordered collection of unique, hashable elements providing high-performance mathematical set operations (union, intersection, symmetric difference) in O(1)O(1) time.

Algorithmic Complexity Comparison

Data StructureMutabilityIndex AccessSearch / Membership (in)Append / AddInsert / Delete (Middle)
ListMutableO(1)O(1)O(n)O(n)O(1)O(1) amortizedO(n)O(n)
TupleImmutableO(1)O(1)O(n)O(n)N/AN/A
DictionaryMutableN/AO(1)O(1) avg / O(n)O(n) worstO(1)O(1) avgO(1)O(1) avg
SetMutableN/AO(1)O(1) avg / O(n)O(n) worstO(1)O(1) avgO(1)O(1) avg

Why we need it

In machine learning pipelines:

  • Choosing the wrong collection ruins performance: Checking if token in token_list inside a loop over a 100,000-word dataset takes minutes (O(n2)O(n^2)), while converting to a set completes in milliseconds (O(n)O(n)).
  • 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.defaultdict form 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:

📄TEXT
[ 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 O(1)O(1) Appending

When a list exceeds its current capacity, CPython allocates a larger contiguous memory buffer according to a geometric growth pattern:

new_allocated≈new_size+(new_size≫3)+6\text{new\_allocated} \approx \text{new\_size} + (\text{new\_size} \gg 3) + 6

Because reallocations happen exponentially less frequently as the list grows, appending is O(1)O(1) amortized. However, inserting or deleting from the beginning (list.insert(0, val)) forces every pointer in the array to shift right, costing O(n)O(n) time.

🐍Python
losses = []
for epoch in range(100):
    losses.append(0.5 / (epoch + 1))  # O(1) amortized append

2. Slicing Mechanics & Shallow Copying

Python slicing syntax follows sequence[start:stop:step]:

  • start: Inclusive starting index (defaults to 0).
  • stop: Exclusive ending index (defaults to len(seq)).
  • step: Stride amount (can be negative for reverse traversal).
🐍Python
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

🐍Python
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:

  1. Memory-efficient: Tuples do not over-allocate extra buffer slots like lists.
  2. Thread-safe: Read-only access prevents race conditions during multithreaded data loading.
  3. Hashable: A tuple containing only hashable elements can be used as a dictionary key or set element.
🐍Python
# 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.85

Typed NamedTuples (typing.NamedTuple)

For clean, self-documenting records without the overhead of full classes:

🐍Python
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:

📄TEXT
# 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 raise TypeError: unhashable type.
🐍Python
# 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] += 1

5. Sets & Mathematical Set Algebra

Python sets are unordered collections of unique hashable elements. They excel at vocabulary extraction, categorical deduplication, and set operations:

🐍Python
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 either
💡

frozenset: 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:

🐍Python
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

🎓
Feynman Teaching Card

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)]`.

✍️
Active Recall Practice

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.

Saved locally on your device

Resources & GitHub

🎯

Mastered this concept?

Tick this box when you feel confident explaining it.

📁
Study Notes & Files1 file

Topic Resources

GitHub↗
🐍

Python_Lists_Tuples_and_Arrays_Reference.py

Python Script

283 B · Modified Latest

Was this clear?