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

前端 未结 3 454
面向向阳花
面向向阳花 2020-12-09 12:13

What is the best approach in python: multiple OR or IN in if statement? Considering performance and best pratices.

if cond == \'1\' or cond         


        
3条回答
  •  -上瘾入骨i
    2020-12-09 13:01

    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.

提交回复
热议问题