I'm learning Python and have seen match-case used to print a weekday for a number. When is it actually a better choice than if-elif-else?
When should I use match-case instead of if-elif-else in Python?
Answers
Match-case is most useful when you're checking the structure of one value, not just comparing it to a few constants. For example, a program handling messages could match a dictionary with a particular message type and pull out the fields that branch needs.
It can also match sequences and objects, with different branches for different shapes. That can keep the checks and unpacking together instead of spreading them across several nested if statements. Python 3.10 or newer is needed.
Reply to this answer
For the weekday example, a list or dictionary is probably simpler. Use a list with day minus one as the index if the input is 1 through 7, and check the range first so invalid values don't give you a misleading result or an error.
A match can still be readable for a handful of fixed values, especially if each case does something different rather than just returning a label.
Reply to this answer
Stick with if-elif when the branches depend on unrelated conditions, ranges, or inequalities. You can add a guard to a match case for an extra condition, but if most of the work is boolean logic, an ordinary if chain is often clearer.
Reply to this answer
A useful way to think about it: match starts with one subject and tries patterns against it. An if-elif chain can test completely different expressions in each branch. Neither is automatically better, so pick the one that makes the decisions easiest to follow.
Reply to this answer
Add your answer
Answers are reviewed before publication.
_permit_pending:
One syntax detail worth learning early: a bare name in a pattern captures a value rather than comparing it to an existing variable. That can be surprising at first.