6
l = ["a", "b", "c", "d", "e"]
if "a" in l and "b" in l and "c" in l and "d" in l:
   pass

What's a shorter way of writing this if statement?

Tried:

if ("a" and "b" and "c" and "d") in l:
    pass

But this seems to be incorrect. What's the correct way? Python 3

rrebase
  • 3,349
  • 2
  • 16
  • 27

5 Answers5

11

An idea might be to use all(..) and a generator:

if all(x in l for x in ['a','b','c','d']):
    pass

All takes as input any kind of iterable and checks that for all elements the iterable emits, bool(..) is True.

Now within all we use a generator. A generator works like:

<expr> for <var> in <other-iterable>

(with no braces)

It thus takes every element in the <other-iterable> and calls the <expr> on it. In this case the <expr> is x in l, and x is the <var>:

#         <var>
#           |
 x in l for x in ['a','b','c','d']
#\----/          \---------------/
#<expr>           <other-iterable>

Further explanation of generators.

metame
  • 2,480
  • 1
  • 17
  • 22
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
6

You can use sets:

l = { 'a', 'b', 'c', 'd', 'e' }

if { 'a', 'b', 'c', 'd' } <= l:
    pass
Alfe
  • 56,346
  • 20
  • 107
  • 159
5
l = "abcde"
if all(c in l for c in "abcd"):
    pass
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
  • 2
    I think the OP is giving an example here with one-char strings, evidently in real life one probably checks against multi-char strings, but good answer nevertheless. – Willem Van Onsem Jan 17 '17 at 22:08
4

A different approach is using sets:

l = ['a', 'b', 'c', 'd', 'e']
if set(['a', 'b', 'c', 'd']).issubset(set(l)):
  pass
Jann
  • 1,799
  • 3
  • 21
  • 38
2

You may also use set objects for such case:

l = ["a", "b", "c", "d", "e"]
if  set(l) >= set(("a", "b", "c", "d")):
    print('pass')

set >= other

Test whether every element in other is in the set.

https://docs.python.org/3/library/stdtypes.html?highlight=set#set.issuperset

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105