A tuple in Python is an ordered, immutable sequence of values, written as items separated by commas, usually inside parentheses: point = (3, 4). You can read its items by index, but you cannot add, remove or replace them after it is created.
The short version of the syntax:
empty = ()
pair = (3, 4)
no_parens = 3, 4
one_item = (5,)
from_list = tuple([1, 2, 3])
How do you create a tuple in Python?
The Python documentation lists four ways to construct one:
- A pair of parentheses for the empty tuple:
() - A trailing comma for a one-item tuple:
a,or(a,) - Items separated by commas:
a, b, cor(a, b, c) - The built-in constructor:
tuple()ortuple(iterable)
The constructor builds a tuple with the same items in the same order as the iterable you give it. In the documentation's own examples, tuple('abc') returns ('a', 'b', 'c') and tuple([1, 2, 3]) returns (1, 2, 3). Called with no argument, it returns (). If you pass something that is already a tuple, you get the same tuple back unchanged.
The items can be any Python objects, and they do not have to be the same type. ('Ada', 36, True) is a valid tuple, and tuples can be nested inside each other.
Why does a one-item tuple need a trailing comma?
The documentation states it directly: it is the comma that makes a tuple, not the parentheses. The parentheses are optional, except for the empty tuple or when they are needed to avoid ambiguity. That is why a single value in parentheses is not a tuple. Parentheses are also used to group expressions, so (5) is just the number 5.
>>> singleton = 'hello',
>>> len(singleton)
1
>>> singleton
('hello',)
Example output, taken from the Python tutorial. Python prints a one-item tuple with its trailing comma so you can tell it apart from a plain value.
The same ambiguity explains the other case where parentheses are required. f(a, b, c) is a function call with three arguments, while f((a, b, c)) passes one 3-item tuple as the only argument.
What does immutable mean for a tuple?
Once a tuple exists, the collection of objects it refers to cannot change. Trying to assign to an item fails:
>>> t = 12345, 54321, 'hello!'
>>> t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Example output, from the Python tutorial. Tuples also have no append, remove or sort methods, because the mutating operations in the documentation are defined only for mutable sequence types such as lists.
If you need a changed version, build a new tuple. Concatenation works because it creates a fresh object and leaves the original alone:
>>> t = (1, 2, 3)
>>> t + (4,)
(1, 2, 3, 4)
>>> t
(1, 2, 3)
Note the comma in (4,). Without it, Python tries to add an integer to a tuple and raises a TypeError.
A tuple can still contain mutable objects
Immutability applies to the tuple's own slots, not to what the items are. The language reference says that if an immutable container holds a reference to a mutable object, its value changes when that object changes, although the container is still considered immutable. In other words, immutable does not strictly mean "unchangeable value".
t = ([1, 2], 3)
t[0].append(4) # allowed: changes the inner list
print(t) # ([1, 2, 4], 3)
t[0] = [] # TypeError: the tuple's own slots can't be reassigned
This matters when you rely on a tuple being constant. A tuple of numbers and strings is fixed. A tuple that holds a list is only as fixed as that list.
What can you do with a tuple?
Tuples implement all of the common sequence operations, so most of what you know from lists and strings applies to reading them:
| Operation | Example | Result |
|---|---|---|
| Index | (10, 20, 30)[0] | 10 |
| Slice | (10, 20, 30)[1:] | (20, 30) |
| Length | len((10, 20, 30)) | 3 |
| Membership | 20 in (10, 20, 30) | True |
| Concatenate | (1, 2) + (3,) | (1, 2, 3) |
| Repeat | (0,) * 3 | (0, 0, 0) |
| Smallest and largest | min((4, 2, 9)), max((4, 2, 9)) | 2, 9 |
Tuples have two methods of their own: count(value) returns how many times a value occurs, and index(value) returns the position of its first occurrence. index raises ValueError if the value is not found.
Tuples are compared lexicographically, item by item. For two tuples to be equal, every item must be equal and they must have the same length.
How does tuple unpacking work?
The statement t = 12345, 54321, 'hello!' is called tuple packing. The reverse is sequence unpacking:
x, y, z = t
This assigns 12345 to x, 54321 to y and 'hello!' to z. The tutorial notes that unpacking needs as many variables on the left as there are elements in the sequence, and that it works for any sequence on the right-hand side. Multiple assignment, such as a, b = 1, 2, is really a combination of tuple packing and sequence unpacking.
Unpacking is also the usual way functions return more than one value. A function that ends with return width, height returns one tuple, and the caller writes width, height = get_size(). The docs mention the starred form too: in 0, *x, 4 with x = [1, 2, 3], the list is spread into the tuple, giving (0, 1, 2, 3, 4).
Tuple vs list: which should you use?
The tutorial's guidance is about the typical shape of the data. Tuples usually contain a heterogeneous sequence of elements that you reach by unpacking or indexing. Lists are mutable, and their elements are usually homogeneous and processed by iterating. A row such as ('Ada', 36, True) is a tuple-style record: each position means something different. A list of usernames is a list-style collection: every item is the same kind of thing, and the number of items may grow.
| Tuple | List | |
|---|---|---|
| Literal | (1, 2, 3) | [1, 2, 3] |
| Change items after creation | No | Yes |
| Typical contents | Mixed types, fixed positions | Same kind of item, variable length |
| Usable as dict key or set item | Yes, if all items are hashable | No |
There is a second, practical reason to choose a tuple. The documentation says tuples are used where an immutable sequence is needed, for example when storing a value in a set or as a dictionary key. That works because immutable sequences support hash():
visited = {(0, 0), (0, 1)}
(0, 1) in visited # True
grid = {(2, 5): "wall"} # (row, column) as a key
The hash support only helps if the contents are hashable too. A tuple that contains a list cannot be used as a key, because the list can change. Python raises TypeError: unhashable type: 'list' when you try.
If you want to convert between the two, tuple(my_list) and list(my_tuple) both build a new object. For more on lists, see Python list comprehension explained, and for the wider picture of the language, Python for beginners: core concepts.
What are named tuples?
Indexing by position gets hard to read once a tuple has more than two or three items. The tutorial points to collections.namedtuple for this: it lets you reach items by attribute name as well as by index. For example, Point = namedtuple('Point', ['x', 'y']) lets you write p.x instead of p[0]. Check the collections documentation for the full options before relying on it for larger records.
Common mistakes
- Forgetting the comma.
x = (5)is the integer 5. Usex = (5,). - Expecting
appendto work. Tuples have noappend. Use a list while you are collecting items, then calltuple(items)when it is finished. - Mismatched unpacking.
a, b = (1, 2, 3)fails because there are three items for two names. Match the counts. - Assuming a tuple is deeply constant. Any list or dictionary inside it can still be changed.
Frequently asked questions
- Is a tuple faster than a list in Python?
- This article does not claim a speed difference, because the Python documentation does not give one. Choose between them by meaning: use a tuple for a fixed group of values and a list for a collection that changes. If speed matters, measure your own code with the timeit module.
- Can you change a tuple in Python?
- You cannot add, remove or replace items in an existing tuple. Assigning to an item, such as t[0] = 5, raises TypeError: 'tuple' object does not support item assignment. To get a different tuple, build a new one, for example with t + (4,). If the tuple holds a mutable object such as a list, that inner object can still be changed.
- Why does a one-item tuple need a comma?
- Because the comma makes the tuple, not the parentheses. Parentheses around a single value are only grouping, as in (5 + 1) * 2. Writing (5,) or 5, tells Python you mean a tuple with one item.
- Can a tuple be a dictionary key?
- Yes, as long as everything inside it is hashable. Python's documentation says immutable sequences such as tuples support hash(), which lets them be used as dict keys and stored in sets. A tuple that contains a list is not hashable, so it fails as a key.