g↗genai/ learner
Python for AI / Lesson 05

Tuples and Sets

Lists let you reorder, replace, and repeat items freely, but AI pipelines also need fixed configuration records that cannot be overwritten and unique ID collections that drop duplicates automatically.

Concept + interactive labBeginner friendly

Tuples and sets: Locked records and unique collections.

In Lesson 04 you used a list ([...]), an ordered, mutable sequence where items can repeat and slots can be changed in place. Here you will add two specialized collections—tuples and sets—and choose between all three using two questions:

  • Are items kept in numbered index slots or deduplicated? A tuple ((...)) keeps items in fixed index order (Slot 0, Slot 1) and allows duplicates, whereas a set ({...} or set()) is an unordered collection of unique items with no index positions.
  • Can slots be changed after creation? A tuple is immutable (its slot bindings are locked once created, and trying to overwrite a slot raises a TypeError, Python's error for an unsupported operation on a data type). You often read a tuple with unpacking, which assigns each slot to its own variable in one line. A set can grow with .add(), but every item stored inside a set must itself be immutable (called hashable, meaning its value and lookup identity stay fixed).
In our running example (illustrative retrieval step)

An AI support pipeline stores fixed model settings in model_spec = ("gpt-4o-mini", 4096) and collects retrieved document IDs from raw_sources = ["doc_12", "doc_05", "doc_12"].

Tuples: Locking ordered records with parentheses and commas.

Think of a printed boarding pass that lists your seat and gate in two fixed boxes: anyone can read Box 0 and Box 1, but you cannot erase and rewrite one box on the card. In Python, a tuple stores an ordered sequence of values separated by commas, usually wrapped in parentheses (...).

In our retrieval example, model_spec = ("gpt-4o-mini", 4096) locks the model name in Slot 0 and the token limit in Slot 1. You can read an item by index (model_spec[0]) or use unpacking to assign every slot to a matching number of variables at once:

model_spec = ("gpt-4o-mini", 4096)
model_name, max_tokens = model_spec # Unpack 2 slots into 2 variables
# Attempting model_spec[1] = 8192 raises:
# TypeError: 'tuple' object does not support item assignment

Because it is the comma that builds a tuple, a single-item tuple must include a trailing comma: required_tag = ("billing",) has type tuple and length 1. Without that comma, ("billing") is just grouping parentheses around a plain str of length 7.

Diagram showing locked tuple model_spec = ("gpt-4o-mini", 4096) with Slot 0: "gpt-4o-mini" and Slot 1: 4096 unpacking downward into model_name = "gpt-4o-mini" and max_tokens = 4096, while model_spec[1] = 8192 -> TypeError is blocked.
Unpacking reads each locked slot into its own variable, while model_spec[1] = 8192 is rejected with a TypeError. (A tuple locks which object sits in each slot; in this lesson we store immutable strings and numbers.)

Outside AI pipelines, a map app often stores a city's (latitude, longitude) coordinates as a tuple such as (37.77, -122.42) so route calculations can unpack both numbers without accidentally overwriting one coordinate.

Sets: Keeping unique items and checking membership.

Think of an event check-in roster that only records whether a badge ID has arrived: scanning the same badge twice still leaves one entry on the roster, and there is no "first seat" or "second seat" number. In Python, a set stores unique, hashable items with no index positions.

When our retrieval step finds three chunks from raw_sources = ["doc_12", "doc_05", "doc_12"], calling unique_sources = set(raw_sources) automatically drops the duplicate "doc_12", leaving two unique IDs:

raw_sources = ["doc_12", "doc_05", "doc_12"]
unique_sources = set(raw_sources) # {"doc_12", "doc_05"} (len is 2)
unique_sources.add("doc_09") # New ID added (len becomes 3)
unique_sources.add("doc_12") # Already present (len stays 3)
has_doc = "doc_05" in unique_sources # True

Watch out for two common set pitfalls:

  • Empty set syntax: Write empty_sources = set() to make an empty set. Writing empty curly braces {} creates an empty dictionary (dict, which we cover in Lesson 06).
  • No indexing or fixed order: Because sets are unordered, display order is arbitrary and unique_sources[0] raises TypeError: 'set' object is not subscriptable.
Diagram showing raw_sources list with "doc_12", "doc_05", and "doc_12" passing through set(raw_sources) into unique_sources containing only "doc_12" and "doc_05" while the extra "doc_12" has Duplicate dropped.
set(raw_sources) keeps one copy of each document ID ("doc_12" and "doc_05") and drops the duplicate "doc_12".

In everyday software, a newsletter signup form can store subscriber email addresses in a set so someone who submits the form twice is only recorded once.

Choosing between lists, tuples and sets.

Use our two criteria—whether items need numbered positions (allowing duplicates) and whether slots should stay locked—to pick the right collection for each step:

CollectionOrder & duplicatesMutability
list
[...]
Ordered by index; keeps duplicatesMutable (edit or append slots)
tuple
(...)
Ordered by index; keeps duplicatesImmutable (slots stay locked)
set
{...} / set()
Unordered (no index); unique items onlyMutable via .add(); items must be hashable
Decision flowchart starting at Unique items only? where Yes leads to Set {"doc_12", "doc_05"} and No leads to Lock slots?, where Yes leads to Tuple ("gpt-4o-mini", 4096) and No leads to List ["doc_12", "doc_05", "doc_12"].
Ask first whether you want only unique items (set), and second whether ordered slots should stay locked (tuple versus list).

In an everyday music app, a song's fixed ID and length in seconds fit a tuple (("track_01", 215)), a play queue where a favorite song can repeat in order fits a list (["track_01", "track_04", "track_01"]), and a filter of unique genre tags fits a set ({"indie", "rock"}).

Quick questions

  • Why is ("billing") a string instead of a tuple? Without a comma, parentheses only group the expression; write ("billing",) with a trailing comma to make a 1-item tuple.
  • How do you create an empty set? Call set(); writing {} creates an empty dictionary (dict).
  • Can you read the first item of a set with unique_sources[0]? No; sets have no index order, so indexing raises a TypeError.
✎ Try it yourselfKnowledge check · Practice only

Choose the right collection for the pipeline step.

In our retrieval pipeline, raw_sources = ['doc_12', 'doc_05', 'doc_12'] contains duplicate document IDs. You want a collection that automatically drops duplicates and lets you check whether 'doc_05' is present with 'doc_05' in unique_sources, without needing index positions. Which Python line creates that collection?

Explore tuples and sets in the retrieval pipeline sandbox.

Before using the sandbox, trace what happens when our pipeline runs model_spec = ("gpt-4o-mini", 4096) and unique_sources = set(raw_sources): unpacking assigns "gpt-4o-mini" and 4096 to separate variables, while set(raw_sources) shrinks ["doc_12", "doc_05", "doc_12"] from 3 items to 2 unique IDs.

Try it in this order:

  1. In Panel 1, click the Trailing comma button to remove the comma from ("billing",) and watch type(required_tag) switch from tuple (len 1) to str (len 7).
  2. Click Try item assignment: model_spec[1] = 8192 to see how Python protects the tuple with a TypeError.
  3. In Panel 2, click + .add("doc_09") (new ID) and then + .add("doc_12") (duplicate) to compare how len(unique_sources) responds.
  4. Switch between the Vision Tile Config and Single-Tag Trap presets, then click Reset sandbox.
Interactive Python simulation

Tuple & Set Retrieval Pipeline Inspector

Illustrative sandbox · Local state

This interactive sandbox simulates Python's tuple and set rules on illustrative retrieval data. In live Python, set display order is arbitrary and not indexed.

Lock model settings in a 2-item tuple and deduplicate retrieved document IDs with a set.

1. Locked Tuple Recordtuple
model_spec = ("gpt-4o-mini", 4096)
model_name, max_tokens = model_spec
required_tag = ("billing",)
Unpacked values:model_name = "gpt-4o-mini", max_tokens = 4096
type(required_tag) & len():tuple (len = 1)
2. Unique Set Filterset
raw_sources = ["doc_12", "doc_05", "doc_12"]
unique_sources = set(raw_sources)
"doc_05" in unique_sources
unique_sources (unindexed):{"doc_12", "doc_05"} (len = 2)
"doc_05" in unique_sources:True
Converted raw_sources list into unique_sources set (1 duplicate dropped).
✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

A developer writes this Python snippet for an AI retrieval step: tag = ("rag") sources = set(["doc_1", "doc_2", "doc_1"]) What are the type of tag and the value of len(sources)?
THE TAKEAWAY

Take this with you.

Use a tuple ((...)) when you want an ordered record whose slots stay locked and can be unpacked into variables—and remember the trailing comma for a 1-item tuple (("billing",)). Use a set ({...} or set() for an empty set) when you want an unordered collection that automatically drops duplicates and checks membership with in.

Next up: Dictionaries in Chapter P1 →