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

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

2. links

Technical Support Engineer of Behavioural Data Platform (Snowplow Analytics). On comparison of programming languages, history of computing, and raw playbooks.