Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way of if statements in python [duplicate]

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

like image 430
rrebase Avatar asked Jan 17 '17 22:01

rrebase


People also ask

Can you have multiple IF statements in Python?

It works that way in real life, and it works that way in Python. if statements can be nested within other if statements. This can actually be done indefinitely, and it doesn't matter where they are nested. You could put a second if within the initial if .

What is shorthand if-else?

The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. (condition) ? expression on true : expression on false.

What is shorthand notation in Python?

“An executable statement, written in so compact manner that it comprises of only a single line of code is known as shorthand statement.”


2 Answers

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.

like image 80
Willem Van Onsem Avatar answered Sep 28 '22 05:09

Willem Van Onsem


You can use sets:

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

if { 'a', 'b', 'c', 'd' } <= l:
    pass
like image 29
Alfe Avatar answered Sep 28 '22 06:09

Alfe