16

I want to use syntax similar to this:

if a in b

but I want to check for more than one item, so I need somthing like this:

if ('d' or 'g' or 'u') in a

but I know it doesn't work.

so I did it this way:

for i in a:
    for j in ['d','g','u']:
        if i==j

and it worked, but I wonder if there's a simpler way.

pyni
  • 185
  • 1
  • 1
  • 6
  • It should return true if __all__ elements are in the list or just a subset of them? – Paulo Bu Mar 26 '14 at 21:50
  • or perhaps if **any** of the elements are in the list? – roippi Mar 26 '14 at 21:50
  • 1
    Check: [**any**](http://docs.python.org/2.7/library/functions.html#any) and [**all**](http://docs.python.org/2.7/library/functions.html#all) in the documentation. – WGS Mar 26 '14 at 21:52

2 Answers2

30

any and all can be used to check multiple boolean expressions.

a = [1, 2, 3, 4, 5]
b = [1, 2, 4]

print(all(i in a for i in b)) # Checks if all items are in the list
print(any(i in a for i in b)) # Checks if any item is in the list
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
8

Use any plus a generator:

if any(x in d for x in [a, b, c]):

Or check for set intersection:

if {a, b, c} & set(d):
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    so this expression (x in d for x in [a, b, c]) is a generator that compares an x in d with an x in [a,b,c] and vice versa? – pyni Mar 30 '14 at 17:42