Why can’t List contain multiple types?

In type theory, a list is a homogenous structure containing values of one type. As such, List only takes a single type, and every element of that list has to have that type.

However, type theory also provides sum types, which you can think of as a wrapper around exactly one value selected from some fixed set of types. A sum type is supported by typing.Union. To specify that a list is a mix of int and str values, use

List[Union[str, int]]

as the type hint.

By contrast, a tuple is an example of a product type, a type consisting of a fixed set of types, and whose values are a collection of values, one from each type in the product type. Tuple[int,int,int], Tuple[str,int] and Tuple[int,str] are all distinct types, distinguished both by the number of types in the product and the order in which they appear.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)