Sub topic 2
Creating tuples, and why the comma matters
This chapter assumes you know basic Python syntax and variables, how lists and indexing work, and how to call functions. By the end you will be able to predict whether an expression builds a tuple or something else. You will also be able to explain why (3) is not a tuple and spot the accidental tuples that a stray comma creates.
The comma builds the tuple
A tuple is an ordered, immutable sequence. The earlier chapter on what tuples are covered why you might want one. This chapter is about how the syntax works. The rule is short: the comma creates the tuple, and the parentheses only group things.
point = (3, 4)
single = (3,)
not_a_tuple = (3)
no_parens = 1, 2, 3
print(type(point), type(single), type(not_a_tuple))
print(no_parens)The first line prints <class 'tuple'> <class 'tuple'> <class 'int'>. The second prints (1, 2, 3).
(3) is the integer 3 wrapped in grouping parentheses, exactly like (2 + 1) * 4. Python has no way to tell grouping from a one-element tuple except by the comma. no_parens shows the same rule from the other side. With no parentheses and with commas, you still get a tuple. When Python displays a tuple it always adds parentheses, which makes it look as if the parentheses were the point.
The empty tuple and the one-element tuple
These two cases are the ones people get wrong.
empty = ()
also_empty = tuple()
print(empty == also_empty, len(empty))
one = 7,
print(one, len(one))
print(type(("a")), type(("a",)))
print(("ab") * 2, ("ab",) * 2)The output is:
True 0
(7,) 1
<class 'str'> <class 'tuple'>
abab ('ab', 'ab')Note three things:
()andtuple()both give the empty tuple. CPython reuses a single empty tuple object, so every empty tuple is the same object. Treat that as an implementation detail and compare with==, notis.- A one-element tuple needs a trailing comma, with or without parentheses. Python prints it as
(7,)for the same reason. ("ab")is just a string, so* 2repeats the characters.("ab",)is a tuple, so* 2repeats the element.
A trailing comma is also allowed after longer tuples. It makes no difference to the value, and it keeps diffs small when you write one item per line:
colors = (
"red",
"green",
"blue",
)
print(len(colors))This prints 3.
When the parentheses are required
Parentheses are optional in many places, so most tuples in real code have them only for readability. They become required when the comma would otherwise be read as something else.
- Function call arguments. A comma in a call separates arguments. To pass one tuple, you need an extra pair of parentheses.
- Nesting. In
((1, 2), (3, 4))the inner parentheses are what keep the pairs together. - Mixing with operators. Commas have the lowest precedence of all, so
1, 2 + 3means(1, (2 + 3)). - The empty tuple. There is nothing else to write.
def show(*args):
print(len(args), args)
show(1, 2)
show((1, 2))
a = 1, 2 + 3
b = (1, 2) + (3,)
print(a)
print(b)The output is:
2 (1, 2)
1 ((1, 2),)
(1, 5)
(1, 2, 3)show(1, 2) passes two arguments. show((1, 2)) passes one argument that happens to be a tuple, so args is a tuple holding a tuple. In a, the + binds tighter than the comma, so only the 2 and 3 are added. For b, the parentheses and the comma after 3 are both needed: (3) would be an int, and tuple + int is an error.
The diagram shows how Python decides what an expression produces.
"Top level" means outside any nested brackets. In [1, 2] the comma belongs to the list, so [1, 2] is a list. In ([1, 2]) there is no top-level comma, so the result is still the list.
Building tuples with tuple()
The tuple() constructor takes any iterable and returns a tuple of its items, in iteration order. Use it when the items already exist in another container or are produced one at a time.
print(tuple([1, 2, 3]))
print(tuple("abc"))
print(tuple({"a": 1, "b": 2}))
print(tuple(n * n for n in range(4)))
print(tuple(range(3)))
try:
tuple(5)
except TypeError as e:
print(e)The output is:
(1, 2, 3)
('a', 'b', 'c')
('a', 'b')
(0, 1, 4, 9)
(0, 1, 2)
'int' object is not iterablePoints worth knowing:
- Iterating a string yields characters, so
tuple("abc")splits it. To make a one-element tuple holding a string, write("abc",), nottuple("abc"). - Iterating a dict yields its keys. Use
tuple(d.items())for key-value pairs. - Iterating a set gives no promised order, so
tuple(some_set)has an arbitrary order. Usetuple(sorted(some_set))when order matters. tuple()takes exactly one iterable argument.tuple(1, 2, 3)raisesTypeError, so write(1, 2, 3).tuple(x)wherexis already a tuple returnsxitself in CPython, because tuples cannot change and copying would gain nothing. Do not depend on that for anything but speed.tuple(some_list)always builds a new object.
There is no tuple comprehension
Square brackets give a list comprehension, and braces give set and dict comprehensions. Parentheses around the same syntax give a generator expression, not a tuple. To get a tuple, wrap the generator in tuple():
gen = (n * 2 for n in range(3))
print(type(gen).__name__)
squares = tuple(n * n for n in range(4))
print(squares)This prints generator and then (0, 1, 4, 9). When tuple() is the only argument, the generator needs no extra parentheses.
Combining and repeating tuples
You cannot change a tuple, but you can build new ones from old ones. + joins two tuples and * repeats one. Both operands of + must be tuples.
base = (1, 2)
print(base + (3,))
print(base * 2)
print((0,) * 5)
try:
base + 3
except TypeError as e:
print(e)The output is:
(1, 2, 3)
(1, 2, 1, 2)
(0, 0, 0, 0, 0)
can only concatenate tuple (not "int") to tuple(0,) * 5 is the usual way to make a fixed-size tuple of defaults. The last error is the first sign of a missing comma, which the next section covers.
Accidental tuples and other comma bugs
Because the comma is what matters, a comma you did not mean to type creates a tuple without any warning.
price = 9.99,
print(price)
try:
total = price + 1
except TypeError as e:
print(e)The output is:
(9.99,)
can only concatenate tuple (not "int") to tupleThe assignment ran without complaint. The failure shows up later, on a different line, with a message about tuples. When you see tuple in an error message for a value you thought was a number or string, look back for a trailing comma where it was assigned. Linters can catch this. Pylint, for example, reports it as trailing-comma-tuple.
The reverse mistake is a missing comma inside a longer tuple of strings:
names = ("ann" "bob")
print(names, type(names).__name__)
names = ("ann", "bob")
print(names, type(names).__name__)The output is:
annbob str
('ann', 'bob') tupleAdjacent string literals are joined at compile time. The first line therefore has no comma at all, so it is a parenthesised string and not a tuple. The mistake also appears inside multi-line tuples, where one missing comma silently merges two items and shortens the tuple by one.
| Expression | Type | Why |
|---|---|---|
| `()` | tuple | Empty tuple, the only case without a comma |
| `(5)` | int | Parentheses only group |
| `(5,)` | tuple | The comma makes it a tuple |
| `5,` | tuple | The parentheses are optional |
| `("a" "b")` | str | No comma; adjacent literals are joined |
| `[5,]` | list | The comma belongs to the list brackets |
| `(n for n in "ab")` | generator | No tuple comprehension exists |
| `tuple("ab")` | tuple | The constructor iterates the string |
Choosing a creation form
- Use a literal such as
(1, 2, 3)when you know the items as you write the code. It is the clearest form and the fastest, and CPython can often build a tuple of constants once at compile time. - Use
tuple(iterable)when the items come from another container or a generator. - Always write the trailing comma for one-element tuples, and keep the parentheses so the comma is hard to miss.
- Prefer parentheses around any tuple that is not the entire right side of an assignment, as in
return, call arguments, and operator expressions, so the grouping is obvious.
Exercise
Predict the type and value of each expression, then run them to check: (a) x = (4), (b) y = 4,, (c) z = tuple("42"), (d) w = ("go",) * 2. Which of these four would make len(...) return 1?
Show answer
(a) x is the int 4. (b) y is the tuple (4,). (c) z is the tuple ('4', '2'), because the string is iterated one character at a time. (d) w is the tuple ('go', 'go'). Only y has length 1. len(x) raises TypeError because an int has no length.
Exercise
This code is meant to hold three file extensions but prints 2. Fix it, then explain which rule was broken: exts = (".py", ".txt" ".md") followed by print(len(exts)).
Show answer
The missing comma between ".txt" and ".md" lets Python join the two literals into ".txt.md", so the tuple has two items. The fix is exts = (".py", ".txt", ".md"), which prints 3. Adjacent string literals are concatenated at compile time, so the omitted comma produces no error.