tuple()
A list that cannot change, and is hashable because of it. That hashability is usually the reason to reach for one.
Demo
tuple copies the items of an iterable into a fixed sequence, exactly like list but without the ability to change afterwards. Watch the one-character case: the result prints as ("x",) with a trailing comma, which is how Python distinguishes a one-item tuple from a parenthesised expression. The empty case prints as () with no comma needed.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| iterable | iterable | no (()) | Any iterable — string, list, set, dict, generator. Omitted gives the empty tuple. |
Return value
tuple — A new tuple holding the items of iterable in order. With no argument, the empty tuple.
Common patterns
cache[(x, y)] = compute(x, y)
return tuple(self._items)
unique_rows = {tuple(row) for row in rows}
Examples
Pitfalls
t = ('a') type(t)
t = ('a',) type(t)
t = ([1], [2]) t[0].append(99) t
t = ((1,), (2,)) hash(t)
hash(([1], 2))
hash(((1,), 2))
tuple('abc')
('abc',)
When to use
- The value must be a dict key or a set member
- Returning a sequence callers should not mutate
- Fixed-shape records where the positions have meaning
- Deduplicating whole rows via a set
- The contents will change → list
- Fields deserve names → collections.namedtuple or a dataclass
- You need uniqueness within the sequence → set or frozenset
Notes
FAQ
Because tuples are immutable, copying one would be pointless — CPython returns the original when the argument is already a tuple. That is safe precisely because nothing can change it, and it is why tuple(t) is t may be True while list(l) is l never is.
t = (1, 2) tuple(t) is t # True