Working with tuples¶
In this tutorial, you will learn how to create and use tuples — Python's immutable sequences.
Time commitment: 15–20 minutes
Prerequisites:
- Python 3.12 or later installed on your machine
- Completion of Working with lists
Learning objectives¶
By the end of this tutorial, you will be able to:
- Create tuples and access items by index
- Unpack tuples into individual variables
- Use tuples as return values from functions
- Understand when to choose tuples over lists
What is a tuple?¶
A tuple is an ordered, immutable sequence of items. Like lists, tuples can hold any type of item — numbers, strings, or even other tuples. The key difference is that once you create a tuple, you cannot change its contents.
Tuples are created using parentheses ():
colours = ("red", "green", "blue")
print(colours)
print(type(colours))
You can also create a tuple without parentheses — Python recognises the commas:
coordinates = 51.5074, -0.1278
print(coordinates)
print(type(coordinates))
Single-item tuples¶
To create a tuple with a single item, you must include a trailing comma. Without the comma, Python treats the parentheses as grouping, not as a tuple:
not_a_tuple = ("hello")
print(type(not_a_tuple)) # This is a string
a_tuple = ("hello",)
print(type(a_tuple)) # This is a tuple
Empty tuples¶
You can create an empty tuple with () or tuple():
empty1 = ()
empty2 = tuple()
print(len(empty1), len(empty2))
Accessing items by index¶
Tuples support the same indexing as lists. Use square brackets with the index position:
colours = ("red", "green", "blue")
print(colours[0]) # First item
print(colours[-1]) # Last item
print(colours[1:]) # Slicing works too
Tuple unpacking¶
One of the most useful features of tuples is unpacking — assigning each item to a separate variable in a single statement:
coordinates = (51.5074, -0.1278)
latitude, longitude = coordinates
print(f"Latitude: {latitude}")
print(f"Longitude: {longitude}")
You can use the * operator to collect remaining items into a list:
scores = (95, 87, 92, 78, 88)
first, second, *rest = scores
print(f"First: {first}")
print(f"Second: {second}")
print(f"Rest: {rest}")
Unpacking also provides an elegant way to swap two variables:
a = 10
b = 20
a, b = b, a
print(f"a = {a}, b = {b}")
Tuples as return values¶
Functions often return tuples when they need to send back multiple values. This is one of the most common uses of tuples in Python:
def min_max(numbers):
"""Return the minimum and maximum of a list of numbers."""
return min(numbers), max(numbers)
lowest, highest = min_max([4, 7, 2, 9, 1])
print(f"Lowest: {lowest}")
print(f"Highest: {highest}")
Named tuples¶
When a tuple represents a record with named fields, you can use namedtuple from the collections module. This makes your code more readable because you can access items by name instead of index:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
origin = Point(0, 0)
destination = Point(3, 4)
print(f"Origin: ({origin.x}, {origin.y})")
print(f"Destination: ({destination.x}, {destination.y})")
Named tuples are still tuples — they support indexing, unpacking, and all other tuple operations:
x, y = destination
print(f"Unpacked: x={x}, y={y}")
print(f"By index: {destination[0]}")
When to use tuples versus lists¶
Use a tuple when:
- The data should not change after creation (for example, coordinates, dates, or configuration)
- You need a hashable value (tuples can be dictionary keys or set members, but lists cannot)
- You are returning multiple values from a function
Use a list when:
- You need to add, remove, or change items
- The collection will grow or shrink over time
- The order of items may need to change
Immutability in practice¶
Because tuples are immutable, any attempt to modify them raises a TypeError:
colours = ("red", "green", "blue")
try:
colours[0] = "yellow"
except TypeError as error:
print(f"Error: {error}")
This immutability is a feature, not a limitation. It means you can trust that a tuple's contents will not change unexpectedly, which makes your code safer and easier to reason about.
Exercise: describe a circle¶
Write a function called describe_circle that takes a radius and returns a tuple containing the circumference and area. Then unpack the result into two variables and print them.
Use the formulas:
- Circumference = 2 × π × radius
- Area = π × radius²
You can use math.pi for the value of π.
# Write your code here
Solution¶
Here is one way to complete the exercise:
import math
def describe_circle(radius):
"""Return the circumference and area of a circle."""
circumference = 2 * math.pi * radius
area = math.pi * radius ** 2
return circumference, area
circumference, area = describe_circle(5)
print(f"Circumference: {circumference:.2f} metres")
print(f"Area: {area:.2f} square metres")
Summary¶
In this tutorial, you learned how to:
- Create tuples using parentheses
()or commas - Access items using positive and negative indices
- Unpack tuples into individual variables
- Use the
*operator for extended unpacking - Return multiple values from functions using tuples
- Create named tuples for readable record-like structures
- Understand when to choose tuples over lists
What is next¶
In the next tutorial, you will explore:
- Dictionaries — key-value pairs for fast lookups and structured data