Python Tutorial
Python Update Tuples
Tuples are unchangeable. To change one, convert it to a list, edit, then convert back.
Workaround
list() → change → tuple().
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)Add or Remove
Same trick: convert, append or remove, convert back. Or concatenate tuples.
thistuple = ("apple", "banana", "cherry")
thistuple = thistuple + ("orange",)
print(thistuple)📘 Real-World Deep Dive
Tuples are immutable; "update" means "make a new tuple with one or two fields replaced". <code>dataclasses.replace</code>, <code>NamedTuple._replace</code>, and slicing/concatenation are the three idioms.
Real-Life Scenario
A small log-line schema as a NamedTuple; modify status and exit code mid-pipeline — never mutate the original.
Real-Life Example
from typing import NamedTuple
class LogEvent(NamedTuple):
ts: str
level: str
status: int
e = LogEvent(ts="2026-08-20T22:00:00", level="INFO", status=200)
# Field replace via _replace
err = e._replace(level="ERROR", status=503)
print("err :", err)
print("orig:", e) # unchanged
# Field replace via dataclasses.replace (works on plain frozen dataclasses)
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Job:
name: str
status: str = "queued"
retries: int = 0
j = Job(name="ingest")
print(j)
running = replace(j, status="running", retries=1)
print(running)
# Tuple concat for shape change
base = ("ingest", "ok")
extended = base + ("partition=hive",) # appends a field
print("extended tuple:", extended)Expected Output
err : LogEvent(ts='2026-08-20T22:00:00', level='ERROR', status=503)
orig: LogEvent(ts='2026-08-20T22:00:00', level='INFO', status=200)
j : Job(name='ingest', status='queued', retries=0)
running : Job(name='ingest', status='running', retries=1)
extended: ('ingest', 'ok', 'partition=hive')Common mistakes
- Tuples have no
.append(); "tuple.append = ..." raises a clearAttributeError. NamedTuple._replacereturns a brand-new tuple — the original stays untouched.- Use
dataclasses.replacefor non-named, frozen dataclasses.
🚀 Performance & Best Practices
- Field replacements are O(1); avoid rebuilding tuples manually with concatenation.
- For large record sizes, prefer small, frozen dataclasses with
__slots__. - Cache
_replacecalls in hot queries.
🧪 Try It Yourself
- Refactor
Jobto a frozen-class with amark_running()method that returns a new instance. - Add a helper
evolve(record, **changes)that handles both NamedTuple and frozen dataclass. - Profile
replace(j, status="running")vs. constructing a fresh instance.