How to check if a number in a list range

Question:

I have a float number x and a list range list_ = [[a, b], [c,d], [e,f]]

How can check if the number x is in the list. It means the function will return True in case of

a<=x <=b
or 
c<=x <=d
or 
e<=x <=f

Otherwise, the function will return False. Could you help me to write a Python code for the function

function (x, list_)--> True/False
Asked By: Moon Lee

||

Answers:

Clean solution:

def function(x, list_):
    return any([l[0] < x < l[1] for l in list_])

Optimized solution:

def function(x, list_):
    for l in list_:
        if l[0] < x < l[1]:
           return True
    return False
Answered By: Ilya
def function(x,list__):
    for [a,b] in list_data:
        if a<=x<=b:
            return True
    return False
Answered By: Md Jahid Hasan

You can simply iterate through the list and find whether it’s in range or not.

I’m generating the variable and the list randomly and calling a function that iterates and checks whether the variable lies within the range of any of the members of the list.

import numpy as np

def find_if_in_range(list_, var) -> bool:
    for i in list_:
        if i[0] <= var <= i[-1]:
            return True
    return False

var = np.random.randint(10)
list_ = np.random.randint(10, size=(3,2), dtype=np.uint8)
print(f"var: {var}")
print(f"list: {list_}")
res = find_if_in_range(list_, var)
print(res)

Output:

var: 0
list: [[0 6]
 [2 7]
 [7 9]]
True

Hope this helps.

Cheers.

Answered By: MinatoNamikaze91

The idiomatic solution would be this:

def f(x: int, ls: List[Tuple[float, float]]) -> bool: 
   return any(a <= x <=b for (a, b) in ls)

Take specific note of the following:

  • Naming a function function is a super poor idea.
  • It is abnormal and therefore a poor idea to name a variable list_ just to avoid overriding a keyword.
  • Using the form any ensures that you quickly quit when you find a valid solution.
  • You can quickly destructure your tuple (or list, if you happen to pass a list) using the for (a, b) in ls clause.
  • This solution is as quick as if you use a for clause, but all of that is premature optimization anyway.
  • Using an explicit destructing ensures you have two and only two elements for your sublist.

It was requested that I check certain inputs:

>>> f(10.1, [[8.1, 12.1], [110, 120]])
True

Seems to work!

If you’re running into NameError, the issue is simply one of the importation of types. You can either define f like so:

def f(x, ls):
    ... // As you would otherwise

Or import the required types to make the type-hinting work properly:

from typing import List, Tuple
def f(x: int, ls: List[Tuple[float, float]]) -> bool: 
    ... // As you would otherwise

This has little to do with the original question or solution – it’s just standard for type hinting in python.

Answered By: Nathaniel Ford
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.