James Hallen
James Hallen

Reputation: 5014

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).

Upvotes: 2

Views: 83

Answers (3)

jamylak
jamylak

Reputation: 133764

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

Upvotes: 6

wim
wim

Reputation: 363596

You can use the subset operator for simple objects such as strings:

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

Here is a general case :

>>> items = ['matt', 'zen', 'a', 'b', 'c', 'cat', 'dog']
>>> all(x in items for x in (['a'], 'b', 'c'))
True

It still works even though we have an unhashable type in the container.

Upvotes: 2

anana
anana

Reputation: 1501

Or

for elem in 'abc':
    if elem in str

Upvotes: 1

Related Questions