Skip to content Skip to sidebar Skip to footer

Python == With Or Vs. In List Comparison

When checking for equality, is there any actual difference between speed and functionality of the following: number = 'one' if number == 'one' or number == 'two': vs. number = 'on

Solution 1:

If the values are literal constants (as in this case), in is likely to run faster, as the (extremely limited) optimizer converts it to a constant tuple which is loaded all at once, reducing the bytecode work performed to two cheap loads, and a single comparison operation/conditional jump, where chained ors involve two cheap loads and a comparison op/conditional jump for each test.

For two values, it might not help as much, but as the number of values increases, the byte code savings over the alternative (especially if hits are uncommon, or evenly distributed across the options) can be meaningful.

The above applies specifically to the CPython reference interpreter; other interpreters may have lower per-bytecode costs that reduce or eliminate the differences in performance.

A general advantage comes in if number is a more complicated expression; my_expensive_function() in (...) will obviously outperform my_expensive_function() == A or my_expensive_function() == B, since the former only computes the value once.

That said, if the values in the tuple aren't constant literals, especially if hits will be common on the earlier values, in will usually be more expensive (because it must create the sequence for testing every time, even if it ends up only testing the first value).

Solution 2:

Talking about functionality - no, these two approaches generally differ: see https://stackoverflow.com/a/41957167/747744

Post a Comment for "Python == With Or Vs. In List Comparison"