Tuples and Unpacking

A sequence that cannot be changed after it is built, and the syntax that takes one apart in a single line.

Overview

A sequence that cannot be changed after it is built, and the syntax that takes one apart in a single line.

In this guide
  1. The difference that matters
  2. Why immutability buys you a dictionary key
  3. Unpacking is the point
  4. Returning more than one thing
  5. The comma is the tuple
  6. Unpacking in places you did not expect
  7. Where the wrong number of names bites
  8. Named tuples, when positions stop being obvious
  9. Why immutability is not just a restriction
  10. Choosing between a tuple, a list and a small class
  11. A worked example: taking a row apart
  12. Tuples compare position by position
  13. Tuples you use without noticing
  14. Immutable does not mean constant
  15. Questions people ask about Tuples and Unpacking
  16. Tuples and Unpacking: recap in one screen

tuples.py

tuples.py Python 3
Output

                    

why_tuples.py

why_tuples.py Python 3
Output

                    

Worth knowing

A tuple is written with commas, not brackets. 1, 2 is already a tuple; the brackets only group it.
Immutable means the tuple cannot be re-pointed, so it can be a dict key or a set member. A list cannot.
a, b = b, a builds a tuple on the right, then unpacks it. That is why the swap needs no temporary.
One element needs a trailing comma: (5,). Without it you have brackets round a number.

Tuples and Unpacking: A Practical Guide

A tuple is a sequence that can't be changed once built. That single restriction is what makes it usable as a dict key, safe to hand around. The natural way to return more than one value.

The difference that matters

A list and a tuple both hold an ordered run of items. Both support indexing, slicing, and iteration. The difference is one word: a tuple is immutable. Once it exists, no element can be replaced, no item can be added, and nothing can be removed. That sounds limiting at first, but it is the source of every advantage tuples have over lists.

Think about what happens when you hand a list to a function. The function can append to it, pop from it, or overwrite any position. Your original list changes, even though you never asked for that. Sometimes that is exactly what you want. Other times it causes bugs that are hard to track down, because the change happens far from the code that notices the problem. A tuple prevents that class of mistake entirely. The function receives the same data, but it cannot alter the sequence behind your back. You get a read-only guarantee without writing any extra checks.

Immutability also makes tuples hashable. That single property is why you can use a tuple as a dictionary key or place it inside a set. A list fails both tests. If Python let you use a mutable key, changing the key after insertion would break the lookup, and the dictionary would silently lose track of the entry. Tuples dodge the problem by never changing.

The other big use is unpacking. When a function returns two or three related values, it returns them as a tuple. The caller writes one assignment line and each value lands in its own variable. No indexing, no temporary container. The code reads like a sentence.

point = (3, 4)
point[0] = 99  # TypeError

That restriction is a feature. Hand a list to a function and it can change the list under you. Hand it a tuple and it cannot. This page covers how to build tuples, why immutability matters for dictionary keys, how unpacking works, how to return multiple values from a function, and the comma rule that trips up every beginner exactly once.

Why immutability buys you a dictionary key

A dict key has to be hashable. This means it must never change. If it changed, the dict would look for it in the wrong place. Lists are mutable. They're unhashable. So They can't be keys. Tuples can.

grid[(2, 3)] = "wall"

That is how you key any of it by a coord pair, a date triple, or any other small fixed group.

Unpacking is the point

Unpacking assigns each spot to a name in one statement:

x, y = point

It isn't a special tuple feature. It works on any sequence. But tuples are where you meet it. The number of names must match the number of items, or Python raises ValueError. This Is a feature. It catches the case where the shape you expected isn't the shape you got.

The swap idiom falls straight out of it:

a, b = b, a

The right-hand side is tested first, into a tuple. Only then unpacked. No temporary variable, and no sorting bug.

Returning more than one thing

Python has no special syntax for multiple return values because it doesn't need any. return min(xs), max(xs) returns a tuple, and the caller unpacks it:

low, high = min_max(values)

This reads better than returning a list. The shape is fixed: just two things, in a known order.

The comma is the tuple

The most common surprise is that brackets don't make a tuple — commas do.

type((5))   # int
type((5,))  # tuple

A single-element tuple needs the trailing comma. It looks like a typo and isn't. This bites when a function is supposed to return one item as a tuple and quietly returns the item instead.

Unpacking in places you did not expect

Unpacking isn't limited to set. It's how a for loop reads pairs:

for name, score in [("ana", 91), ("bo", 78)]:
    print(name, score)

Each item is a two-tuple, and the loop unpacks it into two names on the way in. dict.items() yields tuples. This Is why for k, v in d.items() works at all, and enumerate yields (index, value) for the same reason.

A star collects the middle:

first, *rest = [1, 2, 3, 4]      # first = 1, rest = [2, 3, 4]
head, *body, tail = "a b c d".split()

The starred name always turns a list, even when it captures nothing, which means rest is [] rather than None for a one-item sequence. That is worth knowing before you write if rest is None.

Where the wrong number of names bites

x, y = (1, 2, 3)

raises ValueError: too many values to unpack. That looks like an annoyance and is a safety net: it fires the moment the shape of your data changes. Code that indexed point[0] and point[1] would have carried on quietly with a three-element point and made wrong answers much later.

The same error appears when a function you expected to return two things returns one, which is often the real bug rather than the unpacking.

Named tuples, when positions stop being obvious

Spot-based access stops reading well past two or three fields. record[4] tells no one any of it.

from collections import namedtuple

Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p.x, p[0])        # both work

A named tuple is still a tuple - immutable, hashable, unpackable - but its fields have names. It costs one line and it's the usual answer when a plain tuple has grown past the point where you can note what spot two was.

Why immutability is not just a restriction

It's tempting to read "can't be changed" as a limitation you work around. In practice it's a property you lean on. An immutable object can be shared freely between functions, threads and data structures, because no holder of it can surprise another holder by editing it. That is why the language reaches for tuples in just the places where a surprise would be costly: function args arrive as a tuple, exceptions carry their args as a tuple, and a function returning a few values returns a tuple rather than a list.

The immutability is shallow, and this catches people. A tuple ensures that its slots keep pointing at the same objects. It says nothing about those objects. A tuple holding a list will happily let you append to that list, and the tuple is unchanged as far as Python is concerned, because it still points at the same list. This is also why such a tuple isn't hashable: its contents can change, so any hash found from them would go stale.

Choosing between a tuple, a list and a small class

Three options, and the choice is often about what the spots mean.

A list is right when the items are the same kind of thing and the collection grows, shrinks or gets sorted: a list of scores, a list of users, a queue of jobs. spot carries no meaning beyond order.

A tuple is right when the group is fixed at creation and each spot means a thing exact: a coord pair, an RGB colour, a DB row. spot is the meaning, which is just why the group must not change length.

A small class or a dataclass takes over when there are more than about three fields, or when you find yourself writing a comment to note what spot three was. Names beat spots the moment spots stop being obvious, and a named tuple is the halfway house that keeps tuple action while adding them.

A worked example: taking a row apart

row = ("ana", 91, "physics")

name, score, subject = row
print(f"{name}: {score} in {subject}")

name, *rest = row
print(name, rest)
ana: 91 in physics
ana [91, 'physics']

The first unpacking names all three spots. This Is what you want when the shape is known and fixed. And if the row ever gains a fourth field, the ValueError tells you at once rather than letting the extra value disappear.

The second collects the tail, and the starred name is a list though the source was a tuple. That skew is deliberate: the collected part has no fixed length, so it gets the type that handles varying lengths.

The names in the first line are doing the documenting. row[1] in code three screens away means nothing. score means a thing. That is the real arg for unpacking early — not brevity. But That it converts spots into names at the point where you still note what the spots were.

Tuples compare position by position

Check follows the same rule as sorting a dict word: compare the first elements, and only if they're equal look at the second.

print((1, 2) < (1, 3), (1, 2) < (2, 0), ("a", 2) < ("a", 10))

rows = [("bo", 78), ("ana", 91), ("ana", 43)]
print(sorted(rows))
True True True
[('ana', 43), ('ana', 91), ('bo', 78)]

The second check is the one worth noticing: (1, 2) < (2, 0) is true even though 2 is greater than 0. The first elements already decided it. The later spots are never consulted once an earlier one differs.

This is just why a tuple works as a sort key. key=lambda r: (-r.score, r.name) sorts by score and breaks ties by name, and it does so because tuple check stops at the first difference. each multi-level sort in the track leans on this one rule.

It also means check fails the same way unpacking does when the types do not line up: (1, "a") < (1, 2) raises. Once the first elements tie Python has to compare a string with an int.

Tuples you use without noticing

A good deal of Python hands you tuples whether you asked for them or not, and recognising them shows a few pieces of syntax at once.

A function returning a few values returns a tuple. return a, b builds one and the caller unpacks it. *args collects into a tuple, not a list, which is why you can't append to it inside the function. dict.items(), enumerate and zip all yield tuples. This Is why for k, v in ... works for all three. An exception carries its args in e.args, a tuple. String formatting with % takes one, which is why "%s" % (value,) needs that trailing comma.

And the swap, a, b = b, a, builds a tuple on the right and unpacks it on the left — there's no special swap syntax, just the plain rules applied in both directions in one statement.

The common thread is that a tuple is Python's way of saying "a fixed group of things, in order". Wherever the language needs that, it uses one, which is why learning tuple action pays off far outside the places you write the brackets yourself.

Immutable does not mean constant

Two words get used alike and mean different things, and the confusion causes real bugs.

A tuple is immutable: the object can't be changed after it's built. That is a property of the object.

A name is rebindable: point = (3, 4) followed by point = (5, 6) is just right legal. The first tuple was never modified. The name now refers to a different one. Nothing about immutability stops a variable from being pointed a place else, and Python has no way to prevent that at all — the uppercase naming rule for constants is a request, not a rule.

The hands-on consequence is that handing someone a tuple ensures they can't change *your* object. It doesn't ensure that a name in their code still refers to it later, and it doesn't make the values inside it constant if those values are themselves mutable.

This is the same gap as "rebinding versus mutating" from elsewhere in the track, seen from the other side. Immutability drops one of the two ops. The other one is always available.

Questions people ask about Tuples and Unpacking

Do I need the brackets? often not — the comma makes the tuple. Brackets are for clarity and for cases where precedence would or else take over, such as inside a function call.

How do I make a one-element tuple? (5,) with the trailing comma. (5) is just the number in brackets.

Can I sort a tuple? sorted(t) returns a list. A tuple can't be sorted in place, because that would change it.

Are tuples faster than lists? Slightly to build and slightly smaller, and that is rarely the reason to pick one. Pick by whether the contents should be able to change.

Can a tuple hold a list? Yes, and then it isn't hashable — so it can't be a dict key, though it's a tuple.

What does ValueError: too many values to unpack mean? The right-hand side had more items than you gave names for. often the data changed shape.

Is namedtuple still worth using? Yes for a lightweight immutable record, though a frozen dataclass is often clearer for any of it with action attached.

Can I unpack into an existing list element? Yes — a[0], a[1] = a[1], a[0] is legal. Is how you swap two spots of a list in one statement.

Does unpacking work on a gen? Yes, and it consumes it. The count still has to match. It will run the gen to the end to find out.

Why is *args a tuple rather than a list? Because the args are a fixed group by the time the function starts, and making it immutable stops a function from accidentally altering what it was called with.

Tuples and Unpacking: recap in one screen

  • A tuple is a fixed, sorted group whose spots carry meaning. That is what makes it hashable and safe to hand around.
  • The comma makes the tuple, not the brackets. And a one-element tuple needs the trailing comma.
  • Unpacking turns spots into names, and a wrong count raises right away rather than failing quietly later.
  • Check goes spot by spot and stops at the first difference, which is what makes tuple sort keys work.
  • Immutability is shallow: a tuple holding a list is neither frozen nor hashable.

Check yourself

0 of 3

Answer without scrolling back up.

  1. Why can a tuple be a dictionary key when a list cannot?

  2. What is `type((5))`?

  3. In `a, b = b, a`, why is no temporary variable needed?

Cheat sheet

Tuples and Unpacking

Create tuples, unpack them into separate variables, and learn where an immutable sequence fits better than a list.

PYTHON · vizlearn.in/python/tuples_and_unpacking.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.