How To Find The Nearest Numeric Value Within a List With Python

Pavol Kutaj
1 min readOct 1, 2021

The aim of this page📝 is to show a small function that accepts a list and an integer and returns the closest number from the list to the given value.

“Features” of the 👆 function:

  • type hints
  • Naming Conventions From Uncle Bob’s Clean Code Philosophy
  • Lambdas In Python
  • no assignment statements
  • see the official docs for the proper explainer of min function
  • see Kite’s docs for another, more liberal approach
  • the point is that the min function accepts a keyword key parameter that accepts a function with a single param
  • this param is an item from the iterable (item from a list) you pass to the min in the first place
  • the key=function is a so-called mapping function that transforms each item within a list as per our needs
  • here is returns an absolute value of a difference between a given value and each list item
list = [1,5,6,10]
given_number = 7

abs(1-7) -> 6
abs(5-7) -> 2
abs(6-7) -> 1 -> min -> this item is desired -> 6 #RESULT
abs(10-7) -> 3

2. links

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com