Skip to content

Python match case in list

  • by

You use pattern matching with the match statement to match the case in the list in Python. if it does not, you might need to use traditional conditional statements like if, elif, and else instead.

Python match case in list example

Simple example code.

def process_list(my_list):
    match my_list:
        case [1, 2]:
            print("Found [1, 2]")
        case [3, 4]:
            print("Found [3, 4]")
        case [5]:
            print("Found [5]")
        case _:
            print("Other")


my_list1 = [1, 2]
my_list2 = [3, 4]
my_list3 = [5]
my_list4 = [6, 7]

process_list(my_list1)
process_list(my_list2)
process_list(my_list3)
process_list(my_list4)

Output:

Python match case in list

Please verify if this syntax is accurate for your version of Python:

In this example, we’re using the proposed match statement to match different cases within lists. The match statement provides a way to express pattern matching and conditional execution in a more expressive and structured manner.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading