Structural pattern matching for list of unknown length in Python 3.10

Solution 1:

I think in your case you only need all built-in function.

if all(isinstance(i, int) for i in my_list):
    # Do Something
else:
    # raise Exception("...")

But if you really really want to try this logic via match statement you have to capture the elements first and use match guard to verify the condition, but it's kind of a complicated/unreadable solution in this case.

a = [1, 2]
match a:
    case [*elements] if all(isinstance(i, int) for i in elements):
        print("All elements are int")
    case _:
        raise Exception("Elements are not int")

See Also:

  • Python 3.10 pattern matching (PEP 634) - wildcard in string