Introduction & Syntax
Tuples · Study material
A tuple is an ordered, immutable sequence. Where a list is a collection that changes, a tuple is a fixed record: a point (x, y), an RGB colour, a date, a row from a database, several values returned by a function. Because tuples cannot change, Python can use them as dictionary keys and set items. Tests ask about the details – (5) versus (5,), unpacking errors, a list inside a tuple, and what sorted() returns for a tuple. This topic covers them all, then 50 practice questions run on Python 3.
On this page
- Creating tuples – and why the comma matters
- Immutability (and mutable objects inside a tuple)
- Packing, unpacking, swapping and starred targets
- Returning several values from a function
- Tuples as dictionary keys; hashability
- Comparing and sorting tuples; namedtuple
Creating tuples
It is the comma, not the brackets, that creates a tuple: 1, 2 is a tuple, and (5) is just the int 5 in brackets. A one-item tuple needs a trailing comma: (5,). () is the empty tuple and tuple(iterable) converts any iterable. Indexing, slicing, len, in, + and * work as for lists.
point = (3, 4)
rgb = 255, 128, 0 # the COMMA makes a tuple; brackets are optional
single = ("Python",) # one item needs a trailing comma …
not_tuple = ("Python") # … without it, this is just a string in brackets
empty = ()
from_list = tuple([1, 2, 3])
print(type(rgb).__name__, type(single).__name__, type(not_tuple).__name__)
print(point[0], rgb[-1], from_list[1:], len(empty))
print(point + (5,), ("ab",) * 2, 4 in point)
tuple tuple str
3 0 (2, 3) 0
(3, 4, 5) ('ab', 'ab') TrueTuples are immutable
You cannot assign to an item, append, remove or sort a tuple in place – tuples have only two methods, count() and index(). You can build a new tuple and rebind the name. Immutability is shallow: a tuple that contains a list still lets that list change, and such a tuple is not hashable.
dims = (1920, 1080)
try:
dims[0] = 1280 # tuples cannot be changed …
except TypeError as e:
print("TypeError:", e)
dims = (1280,) + dims[1:] # … but the name can be rebound to a new tuple
print(dims)
record = ("Asha", [91, 85]) # a tuple may hold a MUTABLE object
record[1].append(78) # the list inside can still change
print(record)
TypeError: 'tuple' object does not support item assignment
(1280, 1080)
('Asha', [91, 85, 78])Packing and unpacking
Writing values separated by commas packs them into a tuple; assigning a tuple to several names unpacks it. The number of names must match the number of items (otherwise ValueError), unless one name is starred – it collects the rest as a list. Unpacking also works in for loops and in nested form, and a, b = b, a swaps two variables.
student = ("Ravi", 20, "CSE") # packing
name, age, branch = student # unpacking: one name per item
print(name, age, branch)
a, b = 5, 9
a, b = b, a # swap via a temporary tuple
print(a, b)
head, *tail = (10, 20, 30, 40) # the starred name gets a LIST
print(head, tail)
(x, y), label = (2, 7), "P" # nested unpacking
print(x, y, label)
for city, temp in [("Pune", 31), ("Leh", 9)]: # unpacking in a for loop
print(f"{city}: {temp}°C")
Ravi 20 CSE 9 5 10 [20, 30, 40] 2 7 P Pune: 31°C Leh: 9°C
Returning several values
A function that "returns several values" really returns one tuple, which the caller usually unpacks at once. Built-ins such as divmod() and enumerate() work the same way.
def min_max_avg(values):
return min(values), max(values), sum(values) / len(values) # returns ONE tuple
result = min_max_avg([72, 95, 58, 88])
print(result, type(result).__name__)
low, high, avg = min_max_avg([72, 95, 58, 88]) # unpack straight away
print(f"low={low} high={high} avg={avg}")
q, r = divmod(47, 5) # built-ins return tuples too
print(q, r)
(58, 95, 78.25) tuple low=58 high=95 avg=78.25 9 2
Tuples as dictionary keys
A tuple is hashable when all its items are hashable, so it can be a dictionary key or a set member – perfect for coordinates, (from, to) pairs and composite keys. A list can never be a key.
# Tuples of immutable items are hashable, so they can be dict keys and set items
distance = {("Delhi", "Agra"): 233, ("Delhi", "Jaipur"): 281}
print(distance[("Delhi", "Agra")])
visited = {(0, 0), (1, 2)}
visited.add((1, 2)) # already there
print(len(visited), (0, 0) in visited)
t = (1, 2)
print(hash(t) == hash((1, 2)))
try:
hash((1, [2])) # a list inside makes it unhashable
except TypeError as e:
print("TypeError:", e)
233 2 True True TypeError: unhashable type: 'list'
Comparing and sorting
Tuples compare item by item, left to right, like words in a dictionary. That makes lists of tuples easy to sort by several fields, or with a key function for one field. Note that sorted() always returns a list, even for a tuple.
print((1, 2, 3) < (1, 3), (2,) > (1, 9, 9), (1, 2) == (1, 2.0)) # item by item
marks = [("Ravi", 78), ("Asha", 91), ("Meera", 91), ("Dev", 66)]
print(sorted(marks)) # by name, then marks
print(sorted(marks, key=lambda m: m[1], reverse=True))
print(max(marks, key=lambda m: m[1])) # first of the maxima
t = (3, 1, 3, 2, 3)
print(t.count(3), t.index(2), sorted(t)) # sorted() returns a LIST
True True True
[('Asha', 91), ('Dev', 66), ('Meera', 91), ('Ravi', 78)]
[('Asha', 91), ('Meera', 91), ('Ravi', 78), ('Dev', 66)]
('Asha', 91)
3 3 [1, 2, 3, 3, 3]namedtuple: tuples with field names
collections.namedtuple creates a tuple subclass whose items can also be read by name. It is as light as a tuple, immutable, and far more readable than record[2]. _replace() returns a modified copy and _asdict() converts to a dict.
from collections import namedtuple
Employee = namedtuple("Employee", ["name", "dept", "salary"])
e = Employee("Asha", "IT", 85_000)
print(e)
print(e.name, e[2], e.salary * 12) # by name or by index
raised = e._replace(salary=92_000) # a NEW tuple with one field changed
print(raised.salary, e.salary)
print(e._asdict())
Employee(name='Asha', dept='IT', salary=85000)
Asha 85000 1020000
92000 85000
{'name': 'Asha', 'dept': 'IT', 'salary': 85000}Common mistakes
- ("red") – not a tuple; looping over it walks the characters. Write
("red",). - Unpacking the wrong number of values – ValueError: too many / not enough values to unpack.
- Trying to append or assign – AttributeError / TypeError.
- Expecting sorted(t) to be a tuple – it is a list; use
tuple(sorted(t)). - t + 4 – only tuple + tuple works:
t + (4,). - A list inside a tuple used as a key – unhashable.
Key points to remember
- The comma makes a tuple; (x,) is a one-item tuple.
- Tuples are immutable, but objects inside them may be mutable.
- Only two methods: count() and index().
- Unpacking needs matching counts unless a name is starred.
- return a, b returns one tuple.
- Tuples of immutable items are hashable – valid dict keys.
- sorted() of a tuple returns a list.
Frequently asked questions
When should I use a tuple instead of a list?
For fixed-size records whose fields have meaning by position, for values that must not change, and for dictionary keys. Use a list for a collection of similar items that grows or shrinks.
Are tuples faster than lists?
Slightly: they are smaller in memory and quicker to create, and constant tuples are built once at compile time. The main reasons to use them are safety and hashability, not speed.
How do I "change" a tuple?
Build a new one: t = t[:1] + (99,) + t[2:], or convert to a list, edit, and convert back.
Where can I learn more?
Read Python Tuples and Choosing the Right Collection in the Python tutorial, then practise with the exercises below.