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]