Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match case statement with multiple 'or' conditions in each case

Is there a way to assess whether a case statement variable is inside a particular list? Consider the following scenario. We have three lists:

a  = [1, 2, 3]
b  = [4, 5, 6]
c  = [7, 8, 9]

Then I want to check whether x is in each list. Something like this (of course this is a Syntax Error but I hope you get the point):

match x:
    case in a:
       return "132"
    case in b:
       return "564"
    case in c:
       return "798"

This can be easy with an if-else scenario. Nonetheless, focusing on the match-case, if one has many lists. And big lists, it would be a mundane task to write them like that:

match x:
    case 1 | 2 | 3:
       return "132"
    case 4 | 5 | 6:
       return "564"
    case 7 | 8 | 9:
       return "762"

Is there an easy way to check for multiple conditions for each case, without having to write them down?

I checked for duplicates, but I couldn't find them, I hope I don't miss something. Please be kind and let me know if there is a duplicate question.

like image 526
Grzegorz Avatar asked Dec 14 '25 12:12

Grzegorz


1 Answers

As it seems cases accept a "guard" clause starting with Python 3.10, which you can use for this purpose:

match x:
  case w if w in a:
    # this was the "case in a" in the question
  case w if w in b:
    # this was the "case in b" in the question
  ...

the w here actually captures the value of x, part of the syntax here too, but it's more useful in some other fancy cases listed on the linked whatsnew page.

like image 200
tevemadar Avatar answered Dec 16 '25 09:12

tevemadar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!