A pythonic way to check for multiple items in a list

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 to do this?

Something like (invalid python code follows):

if ('a', 'b', 'c') individual_in my_list:
    # do something
    print my_list
+5
source share
3 answers
if set("abc").issubset(my_list):
    # whatever
+13
source

The simplest form:

if all(x in mylist for x in 'abc'):
    pass

Often, when you have a lot of items in these lists, it is better to use a data structure that can search for items without comparing each of them, for example set.

+10
source

You can use set statements:

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
+3
source

All Articles