Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Ellipsis in a variable-length tuple annotation

Use `tuple[T, ...]` for a tuple of any length, including zero, whose elements must all be compatible with `T`.

Version: Python 3.12

Syntax

tuple[T, ...]
points: tuple[tuple[float, float], ...]

Ellipsis in variable-length tuple annotation: in Python 3.12, write tuple[T, ...] without an import. The literal ... represents Ellipsis. After T, it means the same type applies at every position: the tuple may have zero, one, or more elements. It does not add an element to the tuple.

In tuple[tuple[float, float], ...], only the outer tuple can vary in length. Every inner tuple has exactly two positions, both annotated as float (static typing also accepts int there, without converting values). In contrast, tuple[T] requires exactly one element, and tuple[()] describes only the empty tuple.

The annotation is for static type checking. Python does not enforce tuple lengths or element types at runtime based on the annotation. If you need to validate incoming data, check it explicitly.

Examples

def count_points(points: tuple[tuple[float, float], ...]) -> int:
    return len(points)


print(count_points(()))
print(count_points(((1.0, 2.0),)))
print(count_points(((1.0, 2.0), (3.0, 4.0))))

Result

0
1
2

The program prints `0`, `1`, and `2` on separate lines. In `((1.0, 2.0),)` the comma after the pair makes the outer tuple a one-element tuple. `((1.0,),)` does not match the annotation because the pair is missing its second coordinate.

Related lessons

  • Python · Lesson 13 · Advanced · Version: 5

Sources