Structural pattern for variable number of elements of a specific type

Viewed 42

As a toy example, let's say I wanted to match a sequence of 1 integer, an unknown number of strings, and then 1 boolean. Is that currently possible with the match statement?

If the number of strings is known in advance the problem is trivial, for 2 strings it's just:

match val:
    case [int(), str(), str(), bool()]:
        ...

But can it be done for n strings?

My immediate intuition was to try something like:

match val:
    case [int(), *str(), bool()]:
        ...

But this is a SyntaxError.

Is this currently something that just can't be done with pattern matching?

1 Answers

You can use a guard:

match val:
  case [int(), *v, bool()] if all(isinstance(i, str) for i in v): 
     print('matched')
Related