Python Tuples
Python tuples are ordered collections like lists, but they are immutable: once created, their items cannot be changed, added or removed. Tuples are written with round brackets and are ideal for fixed groups of values such as coordinates or RGB colours.
Create a Tuple
point = (4, 7)
color = (255, 128, 0)
single = ("only",) # the comma makes it a tuple
not_tuple = ("only")
print(point[0], color[-1])
print(len(color))
print(type(single), type(not_tuple))4 0 3 <class 'tuple'> <class 'str'>
A tuple with one item needs a trailing comma. Without it, the parentheses are just grouping and you get a plain string.
Tuples Are Immutable
Trying to change an item raises a TypeError. If you really need a changed version, convert to a list, edit it and convert back.
days = ("Mon", "Tue", "Wed")
try:
days[0] = "Sun"
except TypeError as e:
print("Error:", e)
temp = list(days)
temp.append("Thu")
days = tuple(temp)
print(days)Error: 'tuple' object does not support item assignment
('Mon', 'Tue', 'Wed', 'Thu')Tuple Unpacking
Unpacking assigns each item of a tuple to its own variable. A starred name collects the remaining items into a list.
person = ("Maria", "Garcia", "Madrid", "Spain")
first, last, city, country = person
print(first, city)
name, *rest = person
print(name, rest)Maria Madrid Maria ['Garcia', 'Madrid', 'Spain']
Returning Several Values
A function that returns several values separated by commas actually returns a tuple. Unpacking makes this feel natural.
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([8, 3, 12, 5])
print(low, high)3 12
Tuple vs List
- Use a list for a collection that will grow, shrink or change
- Use a tuple for a fixed record whose items have a set meaning, like (x, y)
- Tuples can be used as dictionary keys and set items; lists cannot
- Tuples are slightly smaller and faster, and signal "do not modify" to readers
- Tuples have only two methods: count() and index()
Named Tuples
collections.namedtuple creates a tuple whose items can also be read by name, which makes code more readable.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 9)
print(p.x, p.y)
print(p)3 9 Point(x=3, y=9)
Frequently asked questions
What is the difference between a tuple and a list in Python?
Lists are mutable and use square brackets; tuples are immutable and use round brackets. Choose tuples for fixed data and lists for data that changes.
How do I create a tuple with one element?
Add a trailing comma: ("apple",). Without the comma Python treats the parentheses as grouping and does not create a tuple.
Can you change a tuple in Python?
Not directly. You can convert it to a list, change the list and convert it back with tuple(), which creates a new tuple.