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

Question:

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?

Asked By: Among Us

||

Answers:

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')
Answered By: Fred

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:
    ...
Answered By: Chris