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")
Asked By: Marty

||

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")
Answered By: YScharf

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")
Answered By: platonp
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.