Python Lists
Store ordered items in lists, fixed records in tuples, and unique values in sets.
Why it matters: Batches of texts are lists. Unique document ids often use sets.
Basics
Lists
A list is ordered and changeable: docs = ["a", "b"]
- Index:
docs[0],docs[-1] - Slice:
docs[:2] - Add:
append() - Length:
len(docs)
Keep list items the same type when you can.
Common mistake: writing docs = docs.append(x). append returns None.
Tiny example
Make a list, then print length and the first item.
chunks = ["intro", "method", "results"]
print(len(chunks))
print(chunks[0])Basics
Tuples and Sets
A tuple is ordered and cannot change: shape = (32, 768)
A set stores unique unordered values. Duplicates are removed.
Use sets to drop duplicate ids. Use x in seen for fast checks.
Common mistake: expecting a set to keep display order.
Tiny example
A fixed tuple and a set that drops duplicates.
shape = (8, 768)
ids = {"d1", "d1", "d2"}
print(shape)
print(ids)Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: mini batch
Slice a list to take the first n items.
In AI / ML: Training and RAG code store texts in lists, then slice them.
example.py
Python
chunks = ["a", "b", "c", "d"]
batch = chunks[:3]
print(len(batch))
print(batch[-1])AI / ML example 2
AI / ML: unique ids
Sets remove duplicate document ids.
In AI / ML: RAG retrievers often return the same id twice.
example.py
Python
retrieved = ["d1", "d4", "d1", "d9"]
print(set(retrieved))Takeaways
- 1Lists are ordered and changeable.
- 2Never assign the result of append().
- 3Sets drop duplicates. Tuples hold fixed records.