Python Tutorial: Tuples
Like a list, but locked. Tuples are immutable — perfect for data that should never change.
Some data should not change
Coordinates, RGB colours, database rows, days of the week — these values are fixed. They should never be modified.
A tuple is an immutable list. Once you create it, the values are locked. Python uses this for safety and performance. Ten steps.
What you'll learn in this Python tuples tutorial
This interactive Python tutorial has 8 hands-on exercises. Estimated time: 16 minutes.
- Like a list, but locked — You know lists — flexible, changeable, great for collections you build up over time.
- Try to change it — it won't work — Tuples are immutable. Trying to change them causes a `TypeError` — Python refuses.
- Unpacking — unbox the values — Tuples support **unpacking** — assign each value to a separate variable in one line:
- The single-element trap — Quick quiz: is `(5)` a tuple?
- List vs Tuple — when to use which — Use a **list** when:
- Tuples as dictionary keys — Here's a superpower tuples have that lists don't: **you can use tuples as dictionary keys**.
- namedtuple — readable tuple fields — `collections.namedtuple` makes tuples even better — you can access fields by name instead of position.
- Build a coordinate mapper — Final challenge — no starter code.
Python Tuples concepts covered
- Some data should not change