'How to find the *smallest* number in the list that is close to a given number in Python?

I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.

Foe e.x.

my_list=[1,10,15,20,45,56]
my_no=9

Output should be equal to 1 Explanation: since 9 comes between 1 and 10 and I want the smaller number, i.e. 1.

Similarly if my_no=3, output is equal to 1

I am new to python, so any help will be much appreciated. Thanks!



Solution 1:[1]

List comprehension is another elegant way to do this.

my_list=[1,10,15,20,45,56]
my_no = 9 
output = max([x for x in my_list if x<=my_no])
print(output) #1 

Solution 2:[2]

You can reduce from functools:

from functools import reduce

i = reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
print(i)

# Output
1

Test

# my_no = 18
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
15

# my_no = 59
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
56

Note: this code doesn't work if my_no < my_list[0]. You have to check it before.

Solution 3:[3]

If you want to stick to basics and want to approach it using for loop and if statement then it can be achieved as follows:

my_list=[1,10,15,20,45,56]
given_number = 9

output=my_list[0]
for x in my_list:
  if(x < given_number and x > output):
    output= x

print(output)

# Output
1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kibromhft
Solution 2 Corralien
Solution 3