porrrwal
porrrwal

Reputation: 179

Range vs Greater than and Less than

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

Upvotes: 2

Views: 5169

Answers (2)

Jab
Jab

Reputation: 27515

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.

Upvotes: 6

Python learner
Python learner

Reputation: 1145

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:

Upvotes: 0

Related Questions