Python Tuples
Beginner Data Structures

Python Tuples

1Python Tuples: overview

A tuple is an ordered collection of values, like a list, except that it is immutable: once created, its items cannot be changed, added or removed.

GoalBy the end you can create and index tuples, unpack them into separate variables, return several values from a function, and decide when a tuple suits better than a list.

Before this lesson: Python Lists

2Python Tuples: diagram

Python Tuplescity"Lisbon"[0][-3]38.72[1][-2]-9.14[2][-1]city[0] reads "Lisbon"; city[0] = "Porto" raises TypeError
A tuple is a row of numbered boxes, just like a list, but the boxes are sealed: you can read any item by its index, but you cannot replace, add or remove items.

3Python Tuples: explained step by step

A tuple groups a few values into a single object. You write one by separating the values with commas, usually inside round brackets:

point = (3, 5)
person = ("Asha", 21, "Delhi")
empty = ()

Reading a tuple works exactly like reading a list: indexes start at 0, negative indexes count from the end, slicing gives you a new tuple, and len(), in and for loops all work.

Python
rgb = (255, 140, 0)
print(rgb[0], rgb[-1])
print(rgb[1:])
print(len(rgb), 140 in rgb)

Immutable: read, never change

The big difference from a list is that a tuple can't be changed after it is created. There is no append() or remove(), and assigning to an index raises a TypeError. Think of this as a promise rather than a limitation: any code that receives a tuple knows nobody will quietly change it. Because they never change, tuples can also be used as dictionary keys and set items, which lists cannot.

The comma makes the tuple

The brackets are mostly there for readability; it is the comma that creates a tuple. That is why a tuple with one item needs a trailing comma: (5) is just the number 5 in brackets, while (5,) is a tuple holding 5.

Packing and unpacking

Writing several values separated by commas packs them into a tuple. Putting several names on the left of = unpacks a tuple into separate variables, one per item. The number of names must match the number of items.

Python
size = 1920, 1080          # packing
width, height = size       # unpacking
print(width, "x", height)

a, b = 1, 2
a, b = b, a                # swap two values in one line
print(a, b)

Several results at once

Because unpacking is so easy, tuples are Python's usual way to hand back more than one result. The built-in divmod() returns the quotient and the remainder together, and a function you write can do the same with return low, high — you'll write your own functions in a later lesson.

Python
hours, minutes = divmod(135, 60)
print(hours, "h", minutes, "min")

Tuple or list?

Use a list for a collection of similar things that may grow or shrink, like the items in a shopping cart. Use a tuple for a fixed group where each position has its own meaning, like a coordinate (x, y), a colour (r, g, b) or a date (year, month, day).

Quick reference: Python Tuples

4Python Tuples: syntax

t = (item1, item2, item3)
t = item1, item2           # brackets are optional
one = (item,)              # one item: trailing comma
t[index]   t[start:stop]   len(t)   item in t
a, b, c = t                # unpack (counts must match)
t.count(value)             # how many times value appears
t.index(value)             # position of the first match

5Python Tuples: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
def min_max(readings):
    return min(readings), max(readings)

temps = (18.5, 22.0, 15.5, 25.0, 20.0)
print("Readings:", len(temps))
print("First:", temps[0], "Last:", temps[-1])

low, high = min_max(temps)
print("Range:", low, "to", high)

city = ("Lisbon", 38.72, -9.14)
name, lat, lon = city
print(f"{name} is at {lat}, {lon}")

result = min_max([7, 3, 9])
print(result, type(result).__name__)
Expected outputReadings: 5
First: 18.5 Last: 20.0
Range: 15.5 to 25.0
Lisbon is at 38.72, -9.14
(3, 9) tuple

7Python Tuples: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1-2A small function returns two values separated by a comma. Python packs them into one tuple and returns that.
  2. Line 4Five temperature readings are stored in a tuple, a good fit because recorded readings should not change.
  3. Line 5-6len() and indexing work just like with a list: index 0 is the first item and -1 the last.
  4. Line 8The returned tuple (15.5, 25.0) is unpacked straight into low and high.
  5. Line 9The two separate variables are printed.
  6. Line 11-12In city, each position means something: name, latitude, longitude. Unpacking gives each one a readable name.
  7. Line 13An f-string puts the three unpacked values into one sentence.
  8. Line 15-16Storing the result without unpacking shows what the function really returns: the tuple (3, 9). type(result).__name__ prints the name of its type, tuple.

8Python Tuples: common mistakes

Trying to change an item

✗ Wrong

point = (3, 5)
point[0] = 10
TypeError: 'tuple' object does not support item assignment

✓ Right

point = (3, 5)
point = (10, point[1])
print(point)

Tuples can't be changed in place. Build a new tuple and assign it to the name, or use a list if the values need to change often.

Forgetting the comma in a one-item tuple

✗ Wrong

colors = ("red")
print(type(colors))
print(len(colors))
Prints <class 'str'> and 3 — colors is a string, not a tuple

✓ Right

colors = ("red",)
print(type(colors))
print(len(colors))

Brackets alone don't make a tuple; the comma does. Add a trailing comma.

Unpacking into the wrong number of names

✗ Wrong

student = ("Asha", 21, "Delhi")
name, age = student
ValueError: too many values to unpack (expected 2)

✓ Right

student = ("Asha", 21, "Delhi")
name, age, _ = student
print(name, age)

Give one name per item. Use _ for values you don't need.

9Python Tuples: exercises

Write your answer, then press Check. The checks run in your browser.

1. Unpack a book record

Write code Easy

Unpack the tuple book into three variables called title, author and year in one line, then print them as:

Dune by Frank Herbert (1965)
Your code
book = ("Dune", "Frank Herbert", 1965)

# unpack book here, then print the sentence

2. Predict: brackets or commas?

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
a = (5)
b = (5,)
c = 1, 2, 3
print(type(a).__name__, type(b).__name__)
print(len(b), len(c))
x, y, z = c
print(z, y, x)

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

Why use a tuple when a list can do everything?

A tuple tells readers the group is fixed, protects it from accidental changes, and can be used as a dictionary key or set item. Tuples are also slightly smaller and faster to create than lists.

How do I change a value in a tuple?

You can't change it in place. Build a new tuple instead, for example with slicing and +, or convert it with list(), change the list, and convert back with tuple().

Do tuples always need brackets?

No, the commas create the tuple. You do need brackets for an empty tuple (), inside function calls such as print((1, 2)), and anywhere they make the code clearer.

Further reading

10Next lesson

Up nextPython UnpackingUnpacking assigns the items of any iterable to several names in one statement, and a * lets one name collect the leftov…

Related:
Python ListsPython UnpackingPython SetsPython Dictionaries

← Python Slicing · All Data Structures lessons · Practise in the IDE