Categories
Python Answers

How to get number closest to a given value from a list of integers with Python?

Spread the love

Sometimes, we want to get number closest to a given value from a list of integers with Python.

In this article, we’ll look at how to get number closest to a given value from a list of integers with Python.

How to get number closest to a given value from a list of integers with Python?

To get number closest to a given value from a list of integers with Python, we can call min with the key argument that gets the absolute difference between the target number and the numbers in the list.

For instance, we write

closest = min(my_list, key=lambda x: abs(x - my_number))

to call min with the my_list number list.

We set key to a function that gets the absolute difference between number x in my_list and my_number with

abs(x - my_number)

Then the number in my_list that’s closes to my_number will be returned.

Conclusion

To get number closest to a given value from a list of integers with Python, we can call min with the key argument that gets the absolute difference between the target number and the numbers in the list.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *