Skip to content
Tuples and Unpacking
step 1/8

Reading — step 1 of 8

Learn

~3 min readLists and Tuples

Lists are for collections that grow, shrink, and change. But not every group of values should be changeable. A GPS coordinate is always two numbers. An RGB color is always three. A return value with both (min, max) is naturally a pair. For these fixed groupings, Python has tuples — immutable sequences that represent a structured record rather than a dynamic collection.

Creating tuples

python

The one-element tuple is the famous trap: (42) is just the integer 42 in parens. (42,) is a tuple of one item. The comma matters more than the parens.

Tuples are immutable

python

You can READ from a tuple with indexing/slicing (point[0], point[:2]), but you cannot MUTATE it. To "change" one, you build a new tuple.

When to choose tuple vs list

  • Tuple — fixed size, fixed meaning per position. The values describe ONE THING with multiple parts. (latitude, longitude), (year, month, day), (red, green, blue).
  • List — variable size, all elements are "the same kind of thing." A list of users. A list of file paths.

A mnemonic: lists are for homogeneous collections; tuples are for heterogeneous records. Not strict, but a useful default.

Unpacking — assign multiple variables at once

The killer feature of tuples is unpacking:

python

The right-hand side is treated as a tuple. The left-hand side names get the corresponding values.

Multiple return values

Functions can return tuples; callers unpack them:

python

This pattern is everywhere in Python. divmod(17, 5) returns (3, 2) — quotient and remainder. enumerate yields (index, value) pairs.

Star-unpacking — gather the rest

Use * to capture multiple values:

python

The starred name is always a list (even when unpacking from a tuple).

Named tuples — readable records

For structured data, raw tuples can be cryptic — point[0] vs point.x. The collections.namedtuple builds a tuple type with named fields:

python

(Modern code often uses dataclass or typing.NamedTuple instead — covered in Python Advanced.)

Common mistakes

  • One-element tuple without the comma: (42) is just 42. Use (42,) or even 42,.
  • Tuples are not for lookup tables — use a dict.
  • Treating tuples as cheap lists — they're not really faster for most operations. Use them for SEMANTIC reasons (immutability, fixed structure), not micro-optimizations.
  • Trying to .append to a tuple — there's no append. The whole point is they don't change.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…