Python Tuples

immutability, unpacking, and named tuples

35 min · interactive lesson with runnable code and 8 graded exercises.

What you'll be able to do

  • Create tuples correctly — including the one-element (42,) gotcha
  • Explain what “immutable” really means when a tuple holds a list
  • Unpack values with *, nesting, and swaps
  • Choose tuple vs list, and use namedtuple for readable records

What is a tuple?

Ordered and immutable

A tuple is an ordered, immutable collection. It supports indexing and slicing just like a list — but once created, it can't change.

Here's the twist: it's the comma that makes a tuple, not the parentheses. Test yourself:

Other ways to build tuples, plus the operations they support:

Immutability

What can and can't change

You can't change, add, or remove items after a tuple is created. There's no append, and item assignment fails:

  • safe to use as dict keys and set members
  • clear intent: “this should not change”
  • a bit lighter than lists
  • great for fixed records

But immutability is shallow. The tuple's slots can't be rebound — yet a mutable object sitting in a slot can still change:

Unpacking

The most useful tuple feature

Unpacking assigns each item to its own name in one line. Try the patterns below — including the ones that fail:

Everyday uses — swapping without a temp variable, looping over pairs, and returning several values:

Tuple vs list

Choosing the right one

Tuples as dict keys

Hashable, so they can be keys

Because tuples are immutable, they can be dictionary keys and set members — perfect for coordinates or composite keys. Lists can't:

Named tuples

Readable, lightweight records

collections.namedtuple gives tuple fields names. You keep immutability, indexing and unpacking, and gain readable attribute access.

Common pitfalls

Spot the bug