matthewgdv
matthewgdv

Reputation: 749

Structural pattern for variable number of elements of a specific type

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?

Upvotes: 3

Views: 99

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You can use a guard:

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

Upvotes: 2

Related Questions