Python · Intermediate

Tuples in Python

8 min readUpdated September 24, 2026Every example verified

In short: A tuple is an ordered, immutable sequence of values, written with commas and usually parentheses, such as (51.4, -0.12). Use one when a group of values belongs together and should not change: a coordinate pair, a colour, or the several results a function hands back at once.

What a tuple is and why it exists

A tuple groups several values into one object that keeps its order and cannot be changed after it is built. Where a list is a collection that grows and shrinks, a tuple is a record: a fixed set of fields that belong together. A pair of map coordinates, a colour as red, green and blue amounts, or a date as year, month and day are natural tuples because the number of parts and the meaning of each part are fixed.

The immutability is the point, not a limitation. Because a tuple cannot change, Python can use it as a dictionary key or a set member, a function can hand one back knowing the caller cannot corrupt shared data, and a reader knows the values will still be the same further down the code. Tuples are also slightly smaller and faster to create than lists, but choose them for meaning first.

Tuples share most sequence behaviour with lists and strings: indexing with t[0], negative indexes, slicing, len(), the in test, iteration in a for loop, and the count() and index() methods. What they lack is every method that mutates: no append, no sort, no item assignment.

The most useful tuple feature is unpacking. Writing name, lat, lon = stop assigns the three parts to three names in one statement. The same mechanism powers swapping two variables with a, b = b, a, looping over pairs with for key, value in items, and collecting the tail of a sequence with a starred name: first, *rest = stop.

Syntax

 Python · syntax
point = (3, 4)             # parentheses are usual
point = 3, 4               # but the comma is what makes the tuple
single = (7,)              # one item needs a trailing comma
empty = ()
from_list = tuple([1, 2])  # convert any iterable

x, y = point               # unpacking
first, *rest = (1, 2, 3)   # a starred name collects the remainder as a list

The comma creates the tuple; parentheses only group. (7) is the integer 7, while (7,) and 7, are one-item tuples.

Creating, indexing and unpacking a tuple

A bus stop is a fixed record: name, latitude, longitude and whether it has a shelter. Watch how indexing, slicing and unpacking each pull values out.

 Python
stop = ("Riverside Market", 51.4, -0.12, True)
print(stop[0])
print(stop[-1])
print(len(stop))
print(stop[1:3])

name, lat, lon, sheltered = stop
print(f"{name} at {lat}, {lon}")
print("sheltered" if sheltered else "open")

first, *details = stop
print(first)
print(details)

Output

Riverside Market
True
4
(51.4, -0.12)
Riverside Market at 51.4, -0.12
sheltered
Riverside Market
[51.4, -0.12, True]

Indexing and slicing work exactly as they do for lists, and a slice of a tuple is a new tuple. Unpacking into four names requires exactly four values. The starred form first, *details takes the first value and gathers everything else into details, which is always a list, even though the source was a tuple.

Returning several values from a function

A function that has two things to report returns one tuple; the caller can unpack it or keep it whole.

 Python
def temperature_range(readings):
    return min(readings), max(readings)

readings = [18.5, 21.0, 17.2, 23.8, 19.9]
low, high = temperature_range(readings)
print(f"low {low}, high {high}, spread {high - low:.1f}")
result = temperature_range(readings)
print(type(result).__name__)
print(result)

Output

low 17.2, high 23.8, spread 6.6
tuple
(17.2, 23.8)

The return line has no parentheses, yet it builds a tuple because of the comma. The first call unpacks it into low and high immediately; the second keeps the whole tuple in result, and type() confirms what it is. Returning a tuple is the standard way for a Python function to give back more than one value.

Tuples as dictionary keys and sortable records

Seat bookings are keyed by a (row, seat) pair, and a list of (name, time) records is sorted by its second field.

 Python
booked = {(3, 12): "Ada", (1, 4): "Femi", (3, 2): "Lena"}
print((3, 12) in booked)
print((2, 1) in booked)

for (row, seat), name in sorted(booked.items()):
    print(f"row {row} seat {seat}: {name}")

lap_times = [("Ines", 62.4), ("Kwame", 59.8), ("Priya", 61.0)]
lap_times.sort(key=lambda entry: entry[1])
print(lap_times[0])

Output

True
False
row 1 seat 4: Femi
row 3 seat 2: Lena
row 3 seat 12: Ada
('Kwame', 59.8)

A tuple of numbers is hashable, so it can be a dictionary key; a list in the same position would raise TypeError. Sorting the items compares the key tuples element by element, so row 1 comes before row 3 and, within row 3, seat 2 before seat 12. The loop header unpacks the nested structure in one go: (row, seat) from the key and name from the value. The last part sorts records by one field using a key function that picks index 1.

Tuple or list?

SituationUse
A fixed group of fields with different meanings, such as (name, price)tuple
A collection that grows, shrinks or is sorted in placelist
A key in a dictionary or a member of a settuple
Returning several values from a functiontuple
Many items of the same kind processed in a looplist

Common mistakes

  • Writing (5) and expecting a one-item tuple

    Why it goes wrong: Parentheses alone only group an expression, so (5) is the integer 5. The comma is what creates a tuple.

    Fix: Add the trailing comma: (5,).

     Python · fix
    single = (5,)
    print(len(single))   # 1
  • Trying to change an item with t[0] = 9

    Why it goes wrong: Tuples do not support item assignment; Python raises TypeError. The object is meant to stay as it was created.

    Fix: Build a new tuple from the parts you keep, or use a list if the data genuinely changes over time.

     Python · fix
    t = (1, 2, 3)
    t = (9,) + t[1:]
    print(t)   # (9, 2, 3)
  • Assuming a tuple makes its contents immutable

    Why it goes wrong: Immutability is shallow. A tuple holding a list still lets you append to that list; only the tuple's own slots are fixed. Such a tuple is also not hashable, so it cannot be a dictionary key.

    Fix: Put immutable values inside a tuple when it needs to be a key or a true constant.

     Python · fix
    t = ([1, 2], "x")
    t[0].append(3)
    print(t)   # ([1, 2, 3], 'x')
  • Unpacking with the wrong number of names

    Why it goes wrong: a, b = (1, 2, 3) raises ValueError: too many values to unpack because the number of names must match the number of values exactly.

    Fix: Match the count, or use a starred name to collect the surplus: a, *b = (1, 2, 3).

Where you use this

Any function that has more than one thing to report is a tuple in waiting. A parser that returns both the parsed value and how many characters it consumed, a search that returns the best match and its score, or a validator that returns a success flag and a message: each returns one tuple, and the caller unpacks it into well-named variables on a single line. Returning a list would work, but it tells the reader nothing about how many items to expect or what each one means.

Tuples also make good composite keys. Storing prices per (product, size) or bookings per (row, seat) in a dictionary is cleaner than concatenating strings like "3-12", which you would only have to split apart again.

 Python · in practice
def parse_price(text):
    value = float(text.strip("$"))
    return value, text.startswith("$")

amount, had_symbol = parse_price("$12.50")

Key points

  • A tuple is an ordered, immutable sequence; the comma creates it, parentheses only group.
  • (x,) is a one-item tuple; (x) is just x.
  • Unpacking assigns each element to a name, a, b, c = t; a starred name collects the rest into a list.
  • A function returns several values by returning one tuple, which the caller unpacks.
  • Tuples of immutable values can be dictionary keys and set members; lists cannot.
  • Immutability is shallow: a list inside a tuple can still be changed.

Try it yourself

The stats function returns only the total. Change it to return both the total and the average as a tuple, unpack the result into two names, and print them on separate lines.

Your program
def stats(values):
    total = sum(values)
    # return the total AND the average as a tuple
    return total

values = [int(x) for x in input().split()]
total = stats(values)
print(total)
Input the program receives: 12 7 9 20
Expected output: 48 12.0

Practise this

Exercises for this lesson are in the Python practice set.

Open the Python playground

Frequently asked questions

What is the difference between a tuple and a list in Python?

Both are ordered sequences that support indexing, slicing and iteration. A list is mutable: you can append, remove, sort and assign items. A tuple is immutable, so it can be a dictionary key or a set member, and it signals that the values form a fixed record. Use a list for a collection of similar items that changes, and a tuple for a fixed group of related fields.

How do you create a tuple with one element?

Put a comma after the value: (5,) or simply 5,. Without the comma, (5) is just the number 5 in parentheses, which is the most common tuple mistake.

Can you change a value inside a tuple?

Not directly; item assignment raises TypeError. You can build a new tuple from parts of the old one, for example t = (new,) + t[1:]. If the contents include a mutable object such as a list, that inner object can still be modified, because tuple immutability only covers the tuple's own slots.

Progress is stored only in this browser.

How this page was checked. Every program on it was run with CPython 3.11 at build time; runs in your browser on CPython 3.14 (Pyodide) by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.