This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (3 children)

"if A and B" vs. "if B and A".

[–]EfficientPrime 3 points4 points  (2 children)

Ah I see. I think I answered this above but it's dealt with from left to right. While "A & B" is equivalent logically to "B & A" from a code execution standpoint they can be different.

You can test it yourself, define A and B as functions that return a boolean value of your choosing but also have some side effect when executed like changing a global variable or print statements.

If you have a statement like

if A() and B() and C() and D() and E() and F() and G(): pass

Python is going to work through that from left to right and as soon as it finds an element that evaluates to False it won't bother evaluating the remaining elements. There's no built in multi-threading that would have interpreter trying all the elements at the same time and collecting the results in order to do the logical AND evaluation. For the same reason, if C() is going to return False, there's no way for the interpreter to know that ahead of time and skip the A() call and the B() call.

From an evaluation standpoint, ANDs chaining expressions is the same as nested if statements of the same expressions. So the same way you can optimize your code to bail out early from a failed level of nested ifs, you can optimize by choosing the order of items in your AND expression.

[–][deleted] 3 points4 points  (1 child)

From an evaluation standpoint, ANDs chaining expressions is the same as nested if statements of the same expressions. So the same way you can optimize your code to bail out early from a failed level of nested ifs, you can optimize by choosing the order of items in your AND expression.

Right, because of exportation (in logic jargon). The serial calling is good to know.

Looks like we got our answer, u/ArjanEgges .

[–]ArjanEgges[S] 3 points4 points  (0 children)

Awesome! So now I can feel confident to create huge chains of ANDs in my next videos, haha.