Search code examples
pythonpandaslistdataframecoercion

If number is not in list return next highest number + python


I need method of checking whether a number exists is a list/series, and if it does not returning the next highest number in the list.

For example:- in the list nums = [1,2,3,5,7,8,20] if I were to enter the number 4 the function would return 5 and anything > 8 < 20 would return 20 and so on.

Below is a very basic example of the premise:

nums = [1,2,3,5,7,8,20]

def coerce_num(x):
    if x in nums:
        return print("yes")
    else:
        return ("next number in list")

coerce_num(9)

If there was a method to do this with pandas dataframe, that would be even better.


Solution

  • Here's one way using standard Python (nums doesn't need to be sorted):

    def coerce_num(x):
        return min((n for n in nums if n >= x), default=None)
    
    >>> coerce_num(4)
    5
    >>> coerce_num(9)
    20
    

    (added default=None in case no numbers are greater than x)