What is Python's equivalent of && (logical-and) in an if-statement?
In Python, the equivalent to &&
is and
. Both conditions need to be True to proceed.
Example:
Syntax specifics and evaluations
Python's and
handles slightly differently than &&
in languages such as C and Java.
Short-circuit logic
Python bases its evaluation on short-circuit logic. If the left operand is False, Python does not evaluate the right operand.
Bitwise vs. logical operation
Don't mix up and
with &
. The first is a logical operator, the latter a bitwise operator.
Non-boolean and array types with logic
When evaluating non-boolean types or arrays using logical and
, Python implicitly calls the __bool__
method. However, when using NumPy arrays, a ValueError
might spring up.
The second logical operator
For logic that needs at least one condition to be true, use the or
operator.
Traps and tricks
Incorrect use of logical operators can lead to either errors or headaches. These tips make your coding life easier:
Say no to bitwise in logic
Avoid using &&
or ||
. Stick to the Pythonic way: and
and or
.
Clean and clear code
For write pythonic and crystal-clear code, obey the PEP 8 style guidelines. The four-space indentation is particularly helpful.
More logical magic
Compound and nested logical operations are on the Python-menu:
Even lists can be an operand for boolean evaluations thanks to Python's implicit bool
calls!
Additional know-how
Non-Boolean operands
Python isn't picky. It can use and
with non-Boolean types, unlike many strictly-typed languages.
Mutable subplot
Be careful when using mutable default arguments with and
. It could lead to unexpected results.
Use short-circuiting
Short-circuiting can improve your program's performance. So place the faster or the likely-to-be-false condition first. The code evaluation won't reach the second operand if the first evaluates to False
.
Was this article helpful?