Home > Enterprise >  Is there a way to define a list data structure with specific element types in Python 3.9 type hintin
Is there a way to define a list data structure with specific element types in Python 3.9 type hintin

Time:09-16

For example, I want to define data structure X, where X is a list with three elements. The first element and third are strings and the second element is an integer. So something like this:

X = List[str, int, str]

Is there a proper way to define something like this?

CodePudding user response:

Lists are normally meant for collections of data of unknown length. A tuple suits better to your use case:

from typing import Tuple

MyType = Tuple[str, int, str]
my_tuple: MyType = ("foo", 42, "bar")

Update: As @sj95126 mentioned in their comment, you don't have to import typing.Tuple starting with Python >= 3.9:

MyType = tuple[str, int, str]
  • Related