Skip to content Skip to sidebar Skip to footer

Python Boolean Evaluation Order

I'm working with linked lists in Python and couldn't quite figure out the error statement it was putting out. This is my code to increment through the nodes from the head of the li

Solution 1:

Arguments evaluate left to right and there is a "principle of economy".

  • In an "and" clause, the first that gives a False value stops the evaluation and returns False.

  • In an "or" clause, the First that returns True stops the evaluation and returns True.

You can use it in your favor, by first evaluating the "safety" condition and then the other.

while current.next_node is not None and value > current.next_node.data:
    current = current.next_node
current.next_node = Node(value, current.next_node)

In this way, the failure of the first condition will always stop the evaluation. And if it returns true, then the second will execute correctly.

In the other version, you may be trying to access current.next_node.data without the safety. And if current is None, it will trigger an exception.

Solution 2:

Python does short circuit evaluation which is why you're seeing the behavior you are. This comes into play in and and or clauses similarly.

With and clauses, if the expression on the left side evaluates to False there is no way the entire statement can evaluate to True (False and anything is False) so it doesn't bother to evaluate the expression on the right-hand side. If the left-hand side of expression is True, then the right-hand one is evaluated to see what the full expression should be.

Similarly, with or clauses, if the expression on the left evaluates to True, there is no way the entire statement can be False since True or anything is always True. So again, the right-hand expression will not be evaluated. But if the left-hand expression is False, the right-hand one must be evaluated to know the value of the entire expression.

You can see this in action here:

>>>deffoo():...print('foo')...return0>>>defbar():...print('bar')...return1>>>foo() and bar()
foo
0

>>>bar() and foo()
bar
foo
0

Post a Comment for "Python Boolean Evaluation Order"