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?
>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')