Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if list includes an element using match case?

I’m trying to check if a single element is in a list using match case. I’m not very familiar with these new keywords so 90% sure I’m using them wrong. Regardless, is there a way to do this?

This is my code. I’m expecting for this to print "hi detected in list. Hi!" and "hello detected in list. Hello!", but the match statement doesn’t seem to work this way.

    mylist= ["hello", "hi", 123, True]
    match mylist:
        case ['hi']:
            print("hi detected in list. Hi!")
        case ['hello']:
            print("hello detected in list. Hello!")

Is there a way to check if a list includes an element using match case?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using match/case is not the most appropriate way to determine if a list contains some particular value. However, to answer the question then:

mylist= ["hello", "hi", 123, True]

for element in mylist:
    match element:
        case 'hello':
            print('hello detected')
        case 'hi':
            print('hi detected')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading