What is the best approach in python: multiple OR or IN in if statement?

The best approach is to use a set:

if cond in {'1','2','3','4'}:

as membership testing in a set is O(1) (constant cost).

The other two approaches are equal in complexity; merely a difference in constant costs. Both the in test on a list and the or chain short-circuit; terminate as soon as a match is found. One uses a sequence of byte-code jumps (jump to the end if True), the other uses a C-loop and an early exit if the value matches. In the worst-case scenario, where cond does not match an element in the sequence either approach has to check all elements before it can return False. Of the two, I’d pick the in test any day because it is far more readable.

Leave a Comment