Python Glossary Русский

all Python 3Tuples (tuple)term

Creating a tuple

creation

A tuple is written with parentheses (), with the tuple() constructor, or as a plain comma-separated list. A single item needs a trailing comma: (x,).

Syntax

()  |  (x,)  |  (a, b)  |  tuple(iterable)

The comma makes the tuple, not the parentheses: (1) is just a number, while a stray trailing comma in x = 5, silently turns 5 into (5,) and later shows up as unexpected parentheses in the output. The tuple() constructor consumes an iterable item by item, so tuple('abc') gives ('a', 'b', 'c') while tuple(5) raises TypeError, because a number is not iterable.

Examples

t0 = ()
# → ()
t1 = (1,)
# → (1,) (не (1) — это просто 1)
t2 = (1, 2, 3)
# → (1, 2, 3)
t3 = 1, 2, 3
# → (1, 2, 3)
t4 = tuple([1, 2, 3])
# → (1, 2, 3)
t5 = tuple('abc')
# → ('a', 'b', 'c')
print(type((1)))
# → <class 'int'> (без запятой — не кортеж!)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy