Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What is the difference between List and Tuple?


Same order and indexing, different promisesList [ ]• Mutable: append, pop, sort• Unhashable, so never a dict key• A collection that grows• Rows read from a CSVTuple ( )• Immutable once created• Hashable if its items are• A fixed record with a shape• (model, text) as a cache key
Immutability is what buys hashability — the reason a tuple can key an embedding cache and a list cannot.

What you need to know

Syntax and the one-item trap

Python
batch = ["doc1", "doc2"]        # list: square bracketspoint = (12.97, 77.59)          # tuple: parentheses (Bengaluru lat, lon)single = ("doc1",)              # a one-item tuple NEEDS the commanot_a_tuple = ("doc1")          # just a str in bracketsprint(type(single).__name__, type(not_a_tuple).__name__)   # tuple str

It is the comma that makes a tuple, not the brackets. x = 1, 2 is also a tuple.

Mutability

Python
batch.append("doc3")            # fineprint(batch)                    # ['doc1', 'doc2', 'doc3']try:    point[0] = 13.0except TypeError as e:    print(e)                    # 'tuple' object does not support item assignment

Immutable means the tuple's slots cannot be reassigned. It is shallow: if a slot holds a list, that list can still change. t = ([1], 2); t[0].append(9) works, and such a tuple is no longer hashable.

Hashable: why tuples can be keys

A hashable object has a hash value that never changes during its life, which is what a dict or set needs to find it again. Immutable objects qualify; lists do not.

ListTuple
Syntax[1, 2, 3](1, 2, 3)
MutableYesNo
Dict key / set memberNoYes, if its items are hashable
Methodsmany (append, sort, ...)two (count, index)
Memorya little more (spare room for growth)a little less
Use fora changing collection of similar itemsa fixed record of related values

Unpacking

Tuples shine when a function returns several values:

Python
def evaluate(preds, labels):    correct = sum(p == l for p, l in zip(preds, labels))    return correct, correct / len(labels)     # returns a tuplecount, accuracy = evaluate([1, 0, 1, 1], [1, 0, 0, 1])print(count, accuracy)                        # 3 0.75

A real-life example

Embedding calls cost money, so a RAG service caches them. The cache key must identify both the model and the text, and it must be hashable:

Python
cache = {}key = ("embed-small-v3", "What is my refund status?")cache[key] = [0.12, -0.05, 0.33]          # list VALUE is fineprint(key in cache)                      # Truetry:    cache[["embed-small-v3", "hi"]] = [0.1]except TypeError as e:    print(e)                             # unhashable type: 'list'                                         # (3.14 words it as "cannot use 'list' as a dict key ...")

The vector itself is a list (in real code, a NumPy array) because it is data you may process; the key is a tuple because it is a fixed identity. If 30% of support questions repeat each day, this one dictionary cuts the embedding bill by roughly the same share.

Follow-up questions to expect

  • "Can a tuple ever change?" — Its slots can't be reassigned, but a mutable object inside it (like a list) can be modified in place.
  • "When would you use a namedtuple or a dataclass instead?" — When the fields deserve names: point.lat reads better than point[0]. Use @dataclass(frozen=True) for an immutable record with type hints.
  • "Is a tuple faster than a list?" — Slightly faster to create and a bit smaller, but choose based on meaning (fixed record or changing collection), not speed.