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 = 'one'
if number in ['one', 'two']:
We’ll learn the best ways of comparing two lists in Python for several use cases where the == operator is not enough. Ready? Let's go! The easiest way to compare two lists for equality is to use the == operator. This comparison method works well for simple cases, but as we'll see later, it doesn't work with advanced comparisons.
What is Python List Difference? Python list difference refers to finding the items that exist in one list, but not in the other. There are two main things to understand here: The comparison ordering matters: if you want to find the items in one list but not in the other, you need to use that are your comparator
Python Comparison Operators ❮ Python Glossary Python Comparison Operators Comparison operators are used to compare two values: Operator Name Example Try it Equal x == y Try it »
The symmetrical difference in Python is a list of items that exist in either list, but not both lists. Recall that with all the methods above, we’re really saying: “these items exist in the comparison list, but not in the other”.
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 or
s 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).
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