Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181280

Pythonic way of checking if several elements are 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 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

Answers (3)

six8
six8

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

Jochen Ritzel
Jochen Ritzel

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

Sven Marnach
Sven Marnach

Reputation: 601539

if set("abc").issubset(my_list):
    # whatever

Upvotes: 13

Related Questions