Python how to type hint a 2D list?
Question:
How do I type check for a 2d list?
I know type checking a 1d list in a functions parameter would be:
apples = list(["granny smith","fiji"])
foo(apples)
def foo(fruits:list):
print("Typed check passed")
But how do it for a 2d list?
board=list([list([1,2]),list([3,4])])
bar(board)
def bar(board:list:list): # My Guess Attempt
print("Type check passed")
Answers:
You can use the generic concrete collections:
# for python >= 3.9
def bar(list[list[int]]):
...
# for older versions:
from typing import List
def bar(List[List[int]]):
...
Assuming, the type of the list elements should be int
– otherwise just use the corresponding type or skip the second set of brackets.
board=list([list([1,2]),list([3,4])])
bar(board)
def bar(board:list[list]):
print("Type check passed")
You are using type hinting, not type checking
You can use this code
from typing import List
def bar(board: List[List[int]]):
# your code
print("Type check passed")
How do I type check for a 2d list?
I know type checking a 1d list in a functions parameter would be:
apples = list(["granny smith","fiji"])
foo(apples)
def foo(fruits:list):
print("Typed check passed")
But how do it for a 2d list?
board=list([list([1,2]),list([3,4])])
bar(board)
def bar(board:list:list): # My Guess Attempt
print("Type check passed")
You can use the generic concrete collections:
# for python >= 3.9
def bar(list[list[int]]):
...
# for older versions:
from typing import List
def bar(List[List[int]]):
...
Assuming, the type of the list elements should be int
– otherwise just use the corresponding type or skip the second set of brackets.
board=list([list([1,2]),list([3,4])])
bar(board)
def bar(board:list[list]):
print("Type check passed")
You are using type hinting, not type checking
You can use this code
from typing import List
def bar(board: List[List[int]]):
# your code
print("Type check passed")