Find the nearest value in Python List

Question:

I have a python list

[2010,2011,2012,2013,2014,2015,2016,2017,2018,2020,2021,2022,2023]

I will get input as product year and I want to search in this list for product year is in the list will get a flag true if the product year is not in the list I want to return the nearest year from the list.

For Example:
The input: 2008

The Output: the nearest product year is 2010

Thanks in advance

Asked By: Muhammad Ibrahim

||

Answers:

Like this:

year_list = [
    2010,2011,2012,2013,2014,2015,2016,2017,2018,2020,2021,2022,2023
]

def find_nearest_year(input_year):
    return min(year_list, key=lambda x:abs(x - input_year)) 

print(f'The nearest product year is {find_nearest_year(2008)}')
# The nearest product year is 2008

print(f'The nearest product year is {find_nearest_year(2018)}')
# The nearest product year is 2018
Answered By: Johnny John Boy

Hope this answer your question

df = pd.DataFrame({'years':[1999,2010,2015,2018,2007,2009,2020]})

ylist = [2010,2011,2012,2013,2014,2015,2016,2017,2018,2020,2021,2022,2023]

def closest(y,ylist):
    if y in ylist:
        return True
    else:
        return ylist[min(range(len(ylist)), key = lambda i: abs(ylist[i]-y))]


df['check'] = df['years'].apply(lambda x: closest(x,ylist))
Answered By: imburningbabe

Code:

#Input
l = [2011,2010,2012,2013,2014,2015,2016,2017,2018,2020,2021,2022,2023] 

# Enter year
yr = int(input('Enter year :'))         

#Here I am  creating new list by deducting the input year  
#like 2011-2008 list elemnt will be 3 list ex: [3,2,4..]                              
minus = [abs(i-yr) for i in l]     


#Lastly to find the near year, by searching the min of minus list
l[minus.index(min(minus))] 

Output:

2010
Answered By: Stackpy
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.