Lists, tuples, and sets
Ordered collections and unique sets — how Python stores batches, token ids, labels, and vocabularies.
Why this matters in AI / ML / GenAI
A batch of texts is a list. Token ids are a list of ints. Evaluation labels are lists. A set is the right tool for unique document ids or a stopword list. You will loop these structures in every training and RAG script.
Lists: the workhorse
A list is an ordered, mutable sequence: docs = ["a", "b"].
- Index:
docs[0],docs[-1] - Slice:
docs[:2](first two — think “mini batch”) - Add:
append,extend - Length:
len(docs)
Lists can hold mixed types, but in ML code keep them homogeneous (all strings, or all floats). Mixed lists become bugs at tensor conversion time.
list.append(x) returns None. A classic bug is docs = docs.append(x), which wipes the list. Append in place; do not assign the result.
Tuples and sets
A tuple is ordered and immutable: shape = (32, 768). Use tuples for records that should not grow — image size, embedding dim, (train, val, test) split sizes.
A set stores unique unordered values: seen = {"id-1", "id-2"}. Membership tests (x in seen) are fast. Use sets to drop duplicate retrieved ids in RAG.
Convert: set(list_of_ids) deduplicates. list(the_set) if you need order back — but set order is not meaningful, so sort if you need stability: sorted(set(ids)).
Copy-paste examples
Copy into your own editor, or load one into the compiler below and press Run.
A mini batch of documents
Slicing a list is how you take the first n chunks into a context window.
chunks = [
"Python is used for ML pipelines.",
"NumPy stores arrays for tensors.",
"pandas cleans tabular data.",
"FastAPI serves models.",
]
batch = chunks[:3]
print("batch size:", len(batch))
print("last in batch:", batch[-1])
batch.append("LangChain wires LLM calls.")
print("after append:", len(batch))Deduplicate retrieved document ids
RAG retrievers often return the same chunk twice. Sets fix that.
retrieved = ["d1", "d4", "d1", "d9", "d4"]
unique_ids = list(dict.fromkeys(retrieved)) # unique, keep order
print("raw:", retrieved)
print("unique ordered:", unique_ids)
print("as set:", set(retrieved))Tuple for a tensor-like shape
Shapes are tuples in NumPy and PyTorch. Do not use a list for a shape you will not change.
batch_size = 8
hidden = 768
shape = (batch_size, hidden)
print("shape:", shape)
print("rank (ndim):", len(shape))
print("total values:", shape[0] * shape[1])Keep the top-k chunks
Try it — in-browser Python
Change k and confirm the printed list length matches.
Output
Python runs in your browser. First run downloads the runtime.
Press Run (or Ctrl+Enter) to execute.
CPython in WebAssembly. Stdlib works. NumPy and pandas load on demand. No input(), no GPU, no network installs.
Takeaways
- Lists are ordered and mutable — batches, token lists, labels.
- Never assign the result of append(); it returns None.
- Sets drop duplicates; tuples hold fixed records like shapes.