Home > Net >  Range vs Greater than and Less than
Range vs Greater than and Less than

Time:10-30

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

CodePudding user response:

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

CodePudding user response:

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:
  • Related