1

I've to use a conditional statement for thousands of entries in a list of lists and I cannot use a dataframe or any other data structure for that matter.
The condition is to check if a number lies in a range let's say >= 10 and <= 20.
Which of the following would be more efficient and why?

if n >= 10 and n <= 20:
    expression
if 10 <= n <= 20:
    expression
if n in range(10, 21):
    expression
porrrwal
  • 169
  • 1
  • 14

2 Answers2

4

The second if is most efficient. Otherwise you're doing a lookup for n 2x or creating a new range every time. See the answers to this question for more clarification.

Jab
  • 26,853
  • 21
  • 75
  • 114
  • I just performed a few dry runs using all the three and the results pretty much reflect your answer. The second one is the most efficient. Thanks. – porrrwal Oct 30 '21 at 06:21
  • It's worth noting that the main performance concern with `n in range(x, y)` from the linked question was primarily a Python 2 thing (the question was from 2012). In Python 3, using `range` is still slower, but by much less (a constant multiple), and the preformance is not dependent on the size of the range at all. That said, there's not really any reason to use it over the chained inequalities unless you specifically want only integer values. – Blckknght Oct 30 '21 at 06:40
  • @Blckknght Although if you want only integers, you could check if it is an int before checking the inequalities and bypass the inequality check if not as well. – Jab Oct 30 '21 at 21:52
0

You can't use range() if the number is a float. By considering time, you can go for interval comparison. I mean,

if 10 <= n <= 21:
Python learner
  • 1,159
  • 1
  • 8
  • 20