You can mix types inside tuples or lists. Why can't you specify that in typing hints?
>>> from typing import Tuple, List
>>> t = ('a', 1)
>>> l = ['a', 1]
>>> t2: Tuple[str, int] = ('a', 1)
>>> l2: List[str, int] = ['a', 1]
TypeError: Too many parameters for typing.List; actual 2, expected 1
A Python list may contain different types! Indeed, you can store a number, a string, and even another list within a single list. Now that your list is created, you can perform two operations on it: 1.
List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.
Create Python Lists A list can have any number of items and they may be of different types (integer, float, string, etc.). A list can also have another list as an item.
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.
You could use a Union
, but generally, if you can avoid it, lists should be homogenous instead of heterogeneous:
from typing import List, Union
lst: List[Union[str, int]] = [1, 'a']
myp
, at least, will accept this just fine.
This means though that your list accessors will return a Union type, often necessitating handling different possible types in any downstream functions. Accepting unions is generally less problematic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With