Reputation: 5014
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
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 set
s:
find = {'a', 'b', 'c'}
for elem in items:
if elem in find:
# do stuff
Upvotes: 6
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