Python annotation's type for nested list with mix of numbers and lists

Question:

It is known that an annotation’s type for [[1, 2, 3], [4, 5, 6], [7, 8, 9]] is List[List[int]]. But what is the annotation’s type for nested list with mix of numbers and lists [[1, 1], 2, [1 , 1]]?

Asked By: illuminato

||

Answers:

Typing has evolved a lot in recent python version, after all it was introduced recently, therefore depending on which version you’re using, the typing signature will be different.

Type of [[1, 2, 3], [4, 5, 6], [7, 8, 9]]:

python version type
>= 3.6 typing.List[typing.List[int]]
>= 3.9 list[list[int]]

Type of [[1, 1], 2, [1 , 1]]:

python version type
>= 3.6 typing.List[typing.Union[typing.List[int], int]]
>= 3.9 list[typing.Union[list[int], int]]
>= 3.10 list[list[int] | int]
Answered By: ljmc
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.