pstatix
pstatix

Reputation: 3848

Why does typing variable length Tuple require ellipses but List does not?

According to the docs:

To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.

So therefore, the annotation Tuple[int] specifies a tuple containing a single integer; yet List[int] implies variable length.

Why must ... be used with Tuple[int, ...] and not with List[int] if both can be homeo/hetero-geneous?

Upvotes: 6

Views: 1466

Answers (1)

deceze
deceze

Reputation: 521994

A tuple is typically used for a small heterogenous set of values of fixed size. Therefore the type hint takes individual arguments denoting the type of each value, e.g. Tuple[str, int, list]. A homogeneous tuple is really a special case, and the ... notation is a shorthand for it.

A list is typically a homogenous sequence of undefined length. Hence its type hint only takes one argument.

Upvotes: 9

Related Questions