Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = 'one'
if number in ['one', 'two']:
like image 942
user2242044 Avatar asked Jun 15 '18 14:06

user2242044


People also ask

How to compare two lists in Python?

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?

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

What are comparison operators in Python?

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 »

What is a symmetrical difference in Python?

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”.


1 Answers

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).

like image 190
ShadowRanger Avatar answered Oct 04 '22 03:10

ShadowRanger