Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching through mutliple values in a list in python

Suppose I have a list:

items = ['matt', 'zen', 'a', 'b', 'c', 'cat', 'dog']

if elem in items 
`if 'a' 'b' 'c' found then return 1

Whenever elem finds 'a', 'b', 'c' in the list and return a value. Is there a way to define the list in such a way? I don't want to have multiple if conditions (if it can be avoided).

like image 436
James Hallen Avatar asked Mar 02 '26 15:03

James Hallen


1 Answers

To check if every item is in items

>>> items = ['matt', 'zen', 'a', 'b', 'c', 'cat', 'dog']
>>> {'a', 'b', 'c'}.issubset(items)
True

Inside a for loop, still taking advantage of the fast (O(1) amortized) lookup speeds of sets:

find = {'a', 'b', 'c'}
for elem in items:
    if elem in find:
        # do stuff
like image 151
jamylak Avatar answered Mar 05 '26 03:03

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!