Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 149 Β· Data Structures

Tuples

Learn Python tuples, the fixed-size sequences you can't change. Create them, index them, pack and unpack values, and meet named tuples for readable records.

A tuple is an ordered sequence of values, just like a list, with one big difference: once you create a tuple, you can't change it. You can't add items, remove items or replace an item. That sounds like a limitation, but it's exactly what you want for data that belongs together and shouldn't drift: a point on a map, a date split into parts, a row read from a file.

Tuples are everywhere in Python, often without you noticing. When a function returns two values, it returns a tuple. When you loop over enumerate() or zip(), each step hands you a tuple. In this lesson you'll learn how to create them, read from them, unpack them into variables and decide when a tuple is a better choice than a list.

Creating tuples

You write a tuple as values separated by commas, usually inside parentheses:

Python Making tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Tuples can hold any mix of types, including other tuples and lists. The len() function tells you how many items a tuple has, exactly as it does for lists and strings.

The comma makes the tuple

Here's a detail that surprises almost everyone: it's the comma that creates a tuple, not the parentheses. The parentheses only group things. That matters most for a tuple with a single item:

Python One-item tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

(42) is the number 42 wrapped in grouping parentheses, the same as (2 + 3) in arithmetic. To make a one-item tuple, add a trailing comma: (42,). It looks odd at first, but you'll get used to it.

Tip: Even though coords = 10, 20 works, most Python developers write the parentheses anyway: coords = (10, 20). It makes the intent obvious to the next reader.

Converting with tuple()

The built-in tuple() turns any iterable into a tuple. This is handy when you have a list but want a frozen copy of it:

Python
letters = tuple("abc")        # ('a', 'b', 'c')
numbers = tuple([4, 5, 6])    # (4, 5, 6)
squares = tuple(n * n for n in range(4))   # (0, 1, 4, 9)

Reading from a tuple

Everything you know about reading from lists works on tuples too: indexing with [], negative indexes, slicing, in, len(), looping and the two methods count() and index().

Python Indexing and slicing

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that a slice of a tuple is itself a tuple. Tuples have only two methods, count() and index(), because every other list method (append, sort, remove and friends) would change the sequence.

Immutability

Try to change a tuple and Python stops you with a TypeError:

Python Tuples can't change

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can't modify a tuple, but you can always build a new one from pieces of the old. The + operator joins tuples and * repeats them, and both produce brand-new tuples. You'll learn more about try and except in Exceptions and try/except; here it simply lets the program print the error and keep going.

Immutable doesn't mean frozen all the way down

A tuple stores references to objects. The tuple itself can't change which objects it holds, but if one of those objects is mutable (like a list), that object can still change:

Python A list inside a tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The tuple still points at the same list; it's the list that grew. Keep this in mind when you need truly fixed data: use tuples of immutable values (numbers, strings, other tuples).

Why immutability is useful

  • Safety. If you pass a tuple to a function, you know it comes back unchanged.
  • Dictionary keys and set members. Only hashable values can be keys in a dictionary or members of a set. A tuple of immutable values is hashable; a list never is. That's why you'll often see keys like (row, column).
  • Meaning. A tuple says "this is one record with a fixed shape". A list says "this is a collection of similar things that may grow or shrink".
Python Tuples as dictionary keys

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Packing and unpacking

Writing several values separated by commas packs them into a tuple. The reverse, spreading a tuple's items into separate variables, is called unpacking:

Python Packing and unpacking

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The number of variables on the left must match the number of items on the right, or Python raises a ValueError. The swap a, b = b, a works because Python first packs the right side into a tuple, then unpacks it into the names on the left.

Functions use the same idea to return several values. A function that ends with return low, high is really returning one tuple, and the caller can unpack it straight away:

Python
def min_max(values):
    return min(values), max(values)

low, high = min_max([4, 9, 1, 7])   # low = 1, high = 9

Unpacking has more tricks, such as collecting "the rest" with a star. You'll see them in Unpacking and Star Expressions.

Named tuples: tuples with field names

person[2] works, but what does index 2 mean? A named tuple lets you read items by name while keeping everything that makes tuples useful. The collections module provides namedtuple, and the typing module provides a class-style version called NamedTuple:

Python Named tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A named tuple is still immutable, so _replace() returns a changed copy instead of editing the original. For records that need defaults, methods or mutability, Python offers data classes, which you'll meet later. The collections lesson covers namedtuple in more depth.

Tuple or list?

A quick rule of thumb:

Use a tuple when… Use a list when…
the data has a fixed number of parts the number of items changes
each position has its own meaning ((lat, lon)) every item has the same meaning (a list of names)
you need a dictionary key or set member you need to sort, append or remove in place
you want to protect data from changes you're building up results step by step

Tuples are also a little smaller in memory and faster to create than lists, but that's rarely the reason to pick one. Choose the type that describes your data best.

Note: sorted() works on tuples too, but it always returns a list. If you need a sorted tuple, wrap it: tuple(sorted(t)).

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Which line creates a tuple with exactly one item?

    The trailing comma makes the tuple. (5) is just the number 5, and tuple(5) fails because an int isn't iterable.
  2. 2. What happens when you run colors = ("red", "green") and then colors[0] = "blue"?

    Tuples are immutable, so item assignment raises TypeError. Build a new tuple if you need different values.
  3. 3. Why can (2, 3) be a dictionary key while [2, 3] can't?

    Dictionary keys must be hashable. A list can change after it's stored, so Python refuses to hash it.
  4. 4. After x, y = 4, 9 and then x, y = y, x, what is x?

    The right side is packed into the tuple (9, 4) first, then unpacked, so x becomes 9 and y becomes 4.

Summary

  • A tuple is an ordered, immutable sequence written with commas, usually inside parentheses: (3, 7).
  • A one-item tuple needs a trailing comma: (42,).
  • Indexing, slicing, len(), in, loops, count() and index() all work like they do for lists.
  • Tuples of immutable values are hashable, so they can be dictionary keys and set members.
  • Packing collects values into a tuple; unpacking spreads them into variables, which also powers swapping and multiple return values.
  • Named tuples (typing.NamedTuple or collections.namedtuple) add readable field names.

Next: Sets, where you'll store unique values and combine collections with union, intersection and difference.