Search code examples
pythonarrayslistnumpymean

finding the element in a list closest to the mean of elements in python?


This is my array a= [5, 25, 50, 100, 250, 500] . The mean value of a is 155 (i calculated using sum(a)/len(a)) but i have to store 100 in a variable instead of 155.

Is there any easy way to solve this problem.


Solution

  • If we want to go with pure python, I would write a function like this:

    from typing import List
    numb_list = [1, 4, 10, 20, 55, 102, 77, 89]
    
    
    def find_closest_to_mean(num_list: List[int])->int:
        mean = sum(numb_list)/len(num_list)
        distance_list = [abs(mean - num) for num in numb_list]
        return num_list[distance_list.index(min(distance_list))]
    
    
    print(find_closest_to_mean(numb_list))  
    

    [Out]

    mean = 44.75
    closest number = 55
    

    here I create a function called find_closest_to_mean that expects a num_list argument that is a list of integers. It then first calculates the mean of the list, creates a distance_list in which each element corresponds to the distance of the num_list in that position with the mean (as an absolute value). lastly it returns an integer from the num_list that has the least distance to the mean.