Search code examples
pythontyping

Python Typing - Specify type for specific index in list


i need to set a specific type for an index in a list (or specify each type individually)

for example:

from typing import List

my_list: List[int, str, int] = [1, 'a', 2] # is something like this possible?

i know typing.TypedDict can specify the type for each key, but is there something like this for a list?


Solution

  • list is the wrong data structure here as the number of elements is generally not fixed in lists. You can do that using a tuple, i.e. my_tuple: tuple[int, str, int].

    -- comment by Selcuk