Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

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

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

if cond == '1' or cond == '2' or cond == '3' or cond == '4' (etc...) :

OR

if cond in ['1','2','3','4']:

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...