Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacements for switch statement in Python?

I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?

like image 892
Michael Schneider Avatar asked Sep 13 '08 00:09

Michael Schneider


People also ask

Can Elif be used an alternative to switch in Python?

Python doesn't support switch-case statements. There was a proposal to introduce Python switch case statements in PEP-3103 but it was rejected because it doesn't add too much value. We can easily implement switch-case statements logic using the if-else-elif statements.

Why switch-case is not used in Python?

Python doesn't have a switch/case statement because of Unsatisfactory Proposals . Nobody has been able to suggest an implementation that works well with Python's syntax and established coding style.

Does Python have a switch statement?

Python does not have a switch statement functionality. But there are ways to replace the switch statement functionality and make the programming easier and faster. This is possible as Python allows us to create our code snippets that work like Switch case statements in any other language.


2 Answers

The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the match-case statement which provides a first-class implementation of a "switch" for Python. For example:

def f(x):     match x:         case 'a':             return 1         case 'b':             return 2         case _:                     return 0   # 0 is the default case if x is not found 

The match-case statement is considerably more powerful than this simple example.


You could use a dictionary:

def f(x):     return {         'a': 1,         'b': 2,     }[x] 
like image 111
Greg Hewgill Avatar answered Sep 16 '22 17:09

Greg Hewgill


If you'd like defaults, you could use the dictionary get(key[, default]) function:

def f(x):     return {         'a': 1,         'b': 2     }.get(x, 9)    # 9 will be returned default if x is not found 
like image 34
Nick Avatar answered Sep 18 '22 17:09

Nick