Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a list to a tuple without angering mypy?

Tags:

python

mypy

I have a list (of length two) and I want to convert it to a tuple

from typing import List, Tuple

l: List[int] = [1, 2]
assert len(l) == 2
t: Tuple[int, int] = tuple(l)

No matter what I do, I get the error message:

Incompatible types in assignment
(expression has type "Tuple[int, ...]", variable has type "Tuple[int, int]")

I've tried splicing

t: Tuple[int, int] = tuple(l)[0:2]
t: Tuple[int, int] = tuple(l[0:2])

and recreating

t: Tuple[int, int] = tuple([l[0], l[1]])
t: Tuple[int, int] = l[0], l[1]  # strangely invalid syntax, even though t = l[0], l[1] is valid

and I've read through the docs, but I haven't found any way to do this cleanly.

like image 897
McKay Avatar asked Sep 13 '25 23:09

McKay


1 Answers

Don't use the tuple function, use the parenthesis syntax.

t: Tuple[int, int] = (l[0], l[1])
like image 60
McKay Avatar answered Sep 16 '25 11:09

McKay