Python tuple and list copy
Preserve a published route as a tuple and make a list when the planner needs an editable draft.
A simple example
tuple and list copy
- Start with An immutable list containing A
- Do this Add B to a new copy
- Result New list A, B
Syntax
draft = list(published)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyAdd a stop to a published bus route
A planner starts with a published route that riders can already see. She needs to add the museum to a draft while keeping the original schedule available to other passengers.
published = ("Station",)
draft = list(published)
draft.append("Museum")
print("[" + ", ".join(draft) + "]")
[Station, Museum]
The draft has two stops while the published route still has just the station.
Extend a draft shortlist
The school office is editing a mutable rehearsal list. Attempt to append one name to the roster. A published read-only list requires a working copy.
Protect a published result
A teacher opens an unmodifiable snapshot of the final roster. Attempt to append one name to the roster. A published read-only list requires a working copy.
What to watch for
Converting a tuple to a list copies the sequence of references. Here its elements are immutable station names.