Tuple types

The type Tuple[T1, …, Tn] represents a tuple with the item types T1, …, Tn:

  1. def f(t: Tuple[int, str]) -> None:
  2. t = 1, 'foo' # OK
  3. t = 'foo', 1 # Type check error

A tuple type of this kind has exactly a specific number of items (2 inthe above example). Tuples can also be used as immutable,varying-length sequences. You can use the type Tuple[T, …] (witha literal – it’s part of the syntax) for thispurpose. Example:

  1. def print_squared(t: Tuple[int, ...]) -> None:
  2. for n in t:
  3. print(n, n ** 2)
  4.  
  5. print_squared(()) # OK
  6. print_squared((1, 3, 5)) # OK
  7. print_squared([1, 2]) # Error: only a tuple is valid

Note

Usually it’s a better idea to use Sequence[T] instead of Tuple[T, …], asSequence is also compatible with lists and other non-tuple sequences.

Note

Tuple[…] is valid as a base class in Python 3.6 and later, andalways in stub files. In earlier Python versions you can sometimes work around thislimitation by using a named tuple as a base class (see section Named tuples).