Tuples in Python
In Python, a tuple
allows you to store ordered collections of data, with the difference that a tuple is immutable: it cannot be modified after its creation (somewhat like a frozenset
). It's an excellent choice when you want to guarantee that your data will not change.
What is a tuple in Python?
A tuple is an immutable data structure.
Once created, its content cannot be modified: neither the elements nor the size.
This makes it safer, especially in cases where you want to ensure that data remains constant (coordinates, colors, fixed parameters...).
Here's an example of a tuple:
coordinates = (48.8566, 2.3522)
This tuple contains two values:
- latitude;
- and longitude.
It's ideal for pairs or groups of fixed data.
Immutability makes tuples faster and more secure than lists in certain situations.
Creating a tuple
To create a tuple, there are several possibilities.
Classic syntax with parentheses
The classic syntax consists of using a pair of parentheses:
colors = ("red", "green", "blue")
Less classic syntax, without parentheses
There's also a syntax that you might find on the internet and in some source codes, which consists of not using parentheses:
coord = 1, 2 # equivalent to (1, 2)
The case of an empty tuple
Here's how it's possible to create an empty tuple:
empty = ()
The case of a tuple with a single element
solo = ("unique",) # the comma is mandatory
This syntax is very important: we must absolutely add a comma after defining our element.
Without this comma, Python would understand the expression as a value surrounded by parentheses. This little experiment demonstrates it:
this_is_a_tuple = (5,)
print(type(this_is_a_tuple)) # Displays "<class 'tuple'>"
this_is_not_a_tuple = (5)
print(type(this_is_not_a_tuple)) # Displays "<class 'int'>
Accessing tuple elements
Just like lists, tuples are indexable! We can therefore access their elements using indexes (0, 1, 2, 3, ...).
colors = ("red", "green", "blue")
print(colors[0]) # red
print(colors[-1]) # blue because we start from the end
You can also iterate through them with loops:
for c in colors:
print(c)
Tuples also support slicing ([start:end]
) like lists.
It's a technique that allows you to extract a sub-part of a tuple.
The first index is included, the second is excluded. This allows, for example, to retrieve the first three elements of a tuple with
my_tuple[0:3]
. You can also use negative values (-1, -2, etc.) to count from the end.PYTHONvalues = (10, 20, 30, 40, 50) print(values[1:4]) # (20, 30, 40) print(values[:3]) # (10, 20, 30) print(values[-2:]) # (40, 50)
Slicing never modifies the original tuple, but it returns a copy of the selected portion. 😉
Tuples and immutability
Immutability is the central characteristic of tuples. Once created, their elements can no longer be modified, deleted, or reassigned.
This is therefore not possible:
colors = ("red", "green", "blue")
colors[0] = "yellow" # ❌ TypeError (cannot reassign)
del colors[1] # ❌ TypeError (cannot delete)
We can only iterate, copy or concatenate its values.
You can also test the presence of an element with
in
:PYTHONprint("red" in colors) # True
It's precisely this immutability that allows tuples to be used as reliable reference values.
Advantages of tuples
Tuples are not just a "locked" version of lists. They have concrete advantages in certain cases:
- Performance: they consume less memory and are slightly faster than lists;
- Security: their immutability prevents accidental modifications;
- Usable as keys: unlike lists, tuples can be hashed, which allows them to be used as dictionary keys or elements of a
set
; - Semantic clarity: they indicate that values are fixed and have a defined order (ex.: coordinates, date, parameters) making them a perfect asset for constants.
For example, it's much more interesting to have a tuple to store geographical coordinates than a list (because coordinates are supposed to work together and therefore should not be modified).
coord = (48.85, 2.35) # Tuple = coordinates (lat, long)
Differences between tuples and lists
Although they share many characteristics (ordered, indexable, iterable), lists and tuples have very different purposes.
Characteristic | list | tuple |
Mutability | ✅ Yes | ❌ No (immutable) |
Performance | Slightly slower | Slightly faster |
Use as key | ❌ No (not hashable) | ✅ Yes (if elements are hashable) |
Syntax | [values] | (values) or value_1, value_2, etc |
Main purpose | Modifiable data | Fixed data (constants) |
When to use a tuple? 🥸
When you want to guarantee data integrity (no modification possible) or create fixed pairs/keys in a dictionary.
Using tuples as dictionary keys
One of the great advantages of tuples is their ability to be used as keys in a dictionary
This is possible because a tuple is hashable (at least as long as it contains only hashable objects (ex.: int, str, float, etc.)).
Example:
students = {
("John", "Smith"): 15,
("Alice", "Martin"): 18
}
Here, the key is a tuple representing the student's full name. This allows managing pairs of data naturally, without concatenating them into a string.
Unpacking and packing tuples
Unpacking allows you to assign the values of a tuple directly to multiple variables, in a single line. It's an elegant way to make code more readable and expressive.
coordinates = (48.8566, 2.3522)
latitude, longitude = coordinates
print(latitude) # 48.8566
print(longitude) # 2.3522
In this example, the two variables respectively receive the first and second elements of the tuple.
This is made possible because a tuple only packs multiple data into a single variable (which creates a tuple).
Assigning multiple variables to a tuple causes its unpacking.
Be careful to respect the number of elements in your tuple:
PYTHONa, b, c = (1, 2) # ❌ ValueError: not enough values
Tuples and multiple assignment
Multiple assignment allows you to initialize multiple variables simultaneously using an implicit tuple.
Example:
x, y = 5, 10
In reality, Python converts this to:
(x, y) = (5, 10)
This is also the basis of swapping variables without a temporary variable:
a, b = 1, 2
a, b = b, a
This is widely used in sorting functions or loops for example! 😋
Useful functions with tuples
Even though tuples are immutable, Python provides several built-in functions to manipulate, analyze or transform them.
Here's a small summary table:
Function | Description |
len(t) | Number of elements in the tuple (comes from length which means size in English) |
min(t) | Element with the smallest value |
max(t) | Element with the largest value |
sum(t) | Sum of numeric elements |
sorted(t) | Returns a sorted list without modifying the original tuple |
tuple(seq) | Convert a sequence (like a character string) to a tuple |
A small example:
grades = (14, 18, 15)
print(len(grades)) # 3
print(max(grades)) # 18
print(sum(grades)) # 47
To iterate through a tuple with indexes, use
enumerate()
:PYTHONfor i, val in enumerate(grades): print(f"Grade {i} : {val}")
Comprehension and generation of tuples
Unlike lists, there is no tuple comprehension ((x for x in iterable)
actually creates a generator, not a tuple).
To create a tuple from an expression, we often use list comprehension with conversion:
squares = tuple([x ** 2 for x in range(5)])
print(squares) # (0, 1, 4, 9, 16)
Be careful not to confuse this with:
PYTHONgen = (x ** 2 for x in range(5)) # This is NOT a tuple but a generator
To transform this generator into a tuple you must use the
tuple()
function:PYTHONsquares = tuple(gen)
This allows you to force the evaluation of the generator to make the values immediately accessible.
Named tuples (namedtuple)
namedtuple
are tuples with field names, available in the collections
module.
They offer increased readability while maintaining the advantages of a tuple like its immutability.
Here's how to use them:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p.x) # 1
print(p.y) # 2
The advantage is that we can now call our elements by their name instead of their index.
Frequently asked questions about tuples
When you start with tuples (not only that actually!) you can ask yourself many questions... Here's a little tour of the most frequently asked questions about tuples.
What's the difference between
tuple
andlist
?
A tuple is immutable (non-modifiable), a list is mutable. The tuple is generally faster and used for constant data.
Can I modify an element of a
tuple
?
No. Once created, a tuple
cannot be modified. It's one of its fundamental principles.
Can a
tuple
contain other types?
Yes! It can contain integers, strings, lists, even other tuples. It can even be empty.
mixed = (1, "Python", [3, 4])
What's the best way to create a
tuple
?
For multiple elements: t = (1, 2, 3)
.
For one: t = (1,)
(don't forget the comma!).
How to really learn Python?
With a comprehensive course on the subject!