Python Tutorial › Data Structures › Tuples

Python Tuples

BeginnerLesson 20 of 479 min read11 runnable examples

A tuple is an ordered collection that cannot be changed after it is created. Use tuples for fixed groups of values, such as coordinates, RGB colours or a database row, and to return several values from a function.

Advertisement
In this lesson
  • Create tuples, including one-item tuples
  • Access items by index and slice
  • Unpack a tuple into variables
  • Know when a tuple beats a list

Create a tuple

Write items separated by commas, usually inside round brackets.

Python
point = (12.5, 77.3)rgb = (255, 128, 0)mixed = ("Asha", 29, True)empty = () print(point, type(point).__name__)print(len(mixed), len(empty))
Output
(12.5, 77.3) tuple
3 0

The commas make the tuple, not the brackets. You can even leave the brackets out:

Python
version = 3, 12, 1print(version)
Output
(3, 12, 1)

The one-item trap

A single value in brackets is just that value. Add a trailing comma to make a one-item tuple:

Python
not_a_tuple = (5)one_item = (5,)print(type(not_a_tuple).__name__, type(one_item).__name__)
Output
int tuple

Access items

Indexing and slicing work exactly as with lists and strings, and a slice of a tuple is a new tuple.

Python
days = ("Mon", "Tue", "Wed", "Thu", "Fri")print(days[0], days[-1])print(days[1:4])print("Wed" in days) for i, day in enumerate(days, 1):    print(i, day, end="  ")
Output
Mon Fri
('Tue', 'Wed', 'Thu')
True
1 Mon  2 Tue  3 Wed  4 Thu  5 Fri  

Tuples are immutable

You cannot add, remove or replace items. Trying to raises a TypeError:

Python
rgb = (255, 128, 0)rgb[0] = 200
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    rgb[0] = 200
    ~~~^^^
TypeError: 'tuple' object does not support item assignment

To “change” a tuple, build a new one:

Python
rgb = (255, 128, 0)rgb = (200,) + rgb[1:]print(rgb)print(rgb * 2)
Output
(200, 128, 0)
(200, 128, 0, 200, 128, 0)
Note

A tuple can contain a mutable object such as a list, and that list can still change. The tuple itself still holds the same objects, so it is called “shallowly” immutable.

Unpacking

Assign a tuple’s items to several names in one step. This is used everywhere in Python.

Python
name, age, city = ("Ravi", 31, "Pune")print(name, age, city) first, *middle, last = (1, 2, 3, 4, 5)print(first, middle, last) def min_max(values):    return min(values), max(values)      # returns a tuple low, high = min_max([7, 2, 9, 4])print(low, high)
Output
Ravi 31 Pune
1 [2, 3, 4] 5
2 9

Tuple methods

Because tuples cannot change, they have only two methods:

Python
marks = (90, 75, 90, 60, 90)print(marks.count(90))print(marks.index(75))print(sorted(marks), min(marks), max(marks), sum(marks))
Output
3
1
[60, 75, 90, 90, 90] 60 90 405

Tuples as dictionary keys

Tuples can be dictionary keys and set members because they are immutable (and hashable). Lists cannot.

Python
distances = {("Pune", "Mumbai"): 150, ("Pune", "Nashik"): 210}print(distances[("Pune", "Mumbai")])
Output
150
Python
bad = {["Pune", "Mumbai"]: 150}
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    bad = {["Pune", "Mumbai"]: 150}
          ^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

Named tuples

collections.namedtuple gives each position a name, so code reads p.x instead of p[0]:

Python
from collections import namedtuple Point = namedtuple("Point", ["x", "y"])p = Point(3, 4)print(p)print(p.x, p.y, p[0])
Output
Point(x=3, y=4)
3 4 3

Check your understanding

Predict the output

t = (1, [2, 3], 4)t[1].append(99)print(t, len(t))

Quick quiz

1. Which of these is a tuple with one item?

2. How many methods does a tuple have?

3. Can a tuple be a dictionary key?

Exercise: student records

Each record is a (name, marks) tuple. Print the topper and the class average, using unpacking in the loop.

Input
[("Asha", 88), ("Ravi", 74), ("Meena", 93)]
Expected output
Topper: Meena 93
Average: 85.0
Hint 1

max(records, key=lambda r: r[1]) finds the record with the highest marks.

Program Practice

Python tuples FAQ

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

A list is mutable and written with [ ]; a tuple is immutable and written with ( ). See List vs Tuple for a full comparison.

How do I create a tuple with one element?

Add a trailing comma: t = (5,) or just t = 5,.

Can I add an element to a tuple?

Not in place. Create a new tuple: t = t + (new_item,).

How do I convert a list to a tuple?

Use tuple(my_list). Use list(my_tuple) to go the other way.

1 thought on “Python Tuples”

Leave a Comment