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.
Before this lesson: Python Lists
2Python Tuples: diagram
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.
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.
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.
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
- Python List vs Tuple: Differences and When to Use Each — A **list** is a changeable (mutable) sequence written with `[]`, while a **tuple** is a fixed (immutable) seq…
- How to Convert a Tuple to a List in Python — Use `list(my_tuple)`, for example `list((1, 2, 3))` returns `[1, 2, 3]`. The unpacking form `[*my_tuple]` doe…
- Python Tuple count() Method — `tuple.count(value)` returns how many items in the tuple are equal to `value`, or `0` if there are none. It i…
- Python Tuple index() Method — `tuple.index(value, start, stop)` returns the position of the **first** item equal to `value` and raises `Val…
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.
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.
- Line 1-2A small function returns two values separated by a comma. Python packs them into one tuple and returns that.
- Line 4Five temperature readings are stored in a tuple, a good fit because recorded readings should not change.
- Line 5-6
len()and indexing work just like with a list: index 0 is the first item and -1 the last. - Line 8The returned tuple
(15.5, 25.0)is unpacked straight intolowandhigh. - Line 9The two separate variables are printed.
- Line 11-12In
city, each position means something: name, latitude, longitude. Unpacking gives each one a readable name. - Line 13An f-string puts the three unpacked values into one sentence.
- 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✓ 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))✓ 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✓ 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 ✓ CompletedUnpack the tuple book into three variables called title, author and year in one line, then print them as:
Dune by Frank Herbert (1965)
book = ("Dune", "Frank Herbert", 1965)
# unpack book here, then print the sentence
book = ("Dune", "Frank Herbert", 1965)
title, author, year = book
print(f"{title} by {author} ({year})")
2. Predict: brackets or commas?
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Then press Check to run it and compare.
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)int tuple
1 3
3 2 1
2 more exercises → 4 more examples
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