Reputation: 181280
I have this piece of code in Python:
if 'a' in my_list and 'b' in my_list and 'c' in my_list:
# do something
print my_list
Is there a more pythonic way of doing this?
Something like (invalid python code follows):
if ('a', 'b', 'c') individual_in my_list:
# do something
print my_list
Upvotes: 5
Views: 325
Reputation: 2990
You can use set operators:
if set('abc') <= set(my_list):
print('matches')
superset = ('a', 'b', 'c', 'd')
subset = ('a', 'b')
desired = set(('a', 'b', 'c'))
assert desired <= set(superset) # True
assert desired.issubset(superset) # True
assert desired <= set(subset) # False
Upvotes: 3
Reputation: 107608
The simplest form:
if all(x in mylist for x in 'abc'):
pass
Often when you have a lot of items in those lists it is better to use a data structure that can look up items without having to compare each of them, like a set
.
Upvotes: 10