Shorter way if statements in python

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

What is a shorter way to write this if statement?

I tried:

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

But that seems wrong. What is the right way? Python 3

+6
source share
5 answers

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

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

Everything takes any type of iteration as input and checks that for all elements emitted by iterable, bool(..) is True .

Now in all we use a generator. The generator works like:

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

(without curly braces)

Thus, it takes each element in <other-iterable> and calls <expr> on it. In this case, <expr> is x in l , and x is <var> :

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

Further explanation of generators .

+11
source

You can use sets:

 l = { 'a', 'b', 'c', 'd', 'e' } if { 'a', 'b', 'c', 'd' } <= l: pass 
+6
source
 l = "abcde" if all(c in l for c in "abcd"): pass 
+5
source

Another approach is to use sets:

 l = ['a', 'b', 'c', 'd', 'e'] if set(['a', 'b', 'c', 'd']).issubset(set(l)): pass 
+4
source

You can also use set objects for this case:

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

set> = other

Check if each item is in a different one.

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

+2
source

Source: https://habr.com/ru/post/1014167/


All Articles