Lists may contain an arbitrary number of elements. There is no way to individually match all of the elements in a list in a case.
You can match all of the elements and then put a guard on the case.
match mylist:
case [*all_elements] if 'hi' in all_elements:
...
This doesn't seem much better than:
if 'hi' in mylist:
...
But let's say you want to determine if list has 'hi' as the first element and includes it again?
match mylist:
case ['hi', *other_elements] if 'hi' in other_elements:
...
Answer from Chris on Stack OverflowIs there a way to match a value against a list of values? I'm trying to do something like this without using a bunch of ifs, but I can't figure out how.
animal = 'dog'
match animal:
case ['dog', 'cat', 'pig']:
print('Mammal!')
case ['crocodile', 'turtle']:
print('Reptile!')
case _:
print('I dont know')python - How to check if list includes an element using match case? - Stack Overflow
Proposal: `for in match` within list comprehension - Ideas - Discussions on Python.org
pattern matching - Using Python's match/case on repeated elements in a list - Stack Overflow
Anyone used match case yet?
Videos
Lists may contain an arbitrary number of elements. There is no way to individually match all of the elements in a list in a case.
You can match all of the elements and then put a guard on the case.
match mylist:
case [*all_elements] if 'hi' in all_elements:
...
This doesn't seem much better than:
if 'hi' in mylist:
...
But let's say you want to determine if list has 'hi' as the first element and includes it again?
match mylist:
case ['hi', *other_elements] if 'hi' in other_elements:
...
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')