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
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 .
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.
“An executable statement, written in so compact manner that it comprises of only a single line of code is known as shorthand statement.”
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.
You can use sets:
l = { 'a', 'b', 'c', 'd', 'e' }
if { 'a', 'b', 'c', 'd' } <= l:
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With