Python program to get average heights of distinct entries

Suppose we have a set of heights where there may be some duplicate entries. We need to find the average of distinct entries from these heights.

So, if the input is like heights = [96,25,83,96,33,83,24,25], then the output will be 52.2 because the unique elements are [96,25,83,33,24], so sum is 96 + 25 + 83 + 33 + 24 = 261, average is 261/5 = 52.2.

Algorithm

To solve this problem, we will follow these steps ?

  • h_set := a set from heights to remove duplicates

  • return sum of h_set items / size of h_set

Example

Let us see the following implementation to get better understanding ?

def solve(heights):
    h_set = set(heights)
    return sum(h_set) / len(h_set)

heights = [96, 25, 83, 96, 33, 83, 24, 25]
print("Heights:", heights)
print("Unique heights:", sorted(set(heights)))
print("Average of distinct heights:", solve(heights))
Heights: [96, 25, 83, 96, 33, 83, 24, 25]
Unique heights: [24, 25, 33, 83, 96]
Average of distinct heights: 52.2

How It Works

The set() function automatically removes duplicate values from the list. Then we calculate the sum of unique values and divide by the count of unique elements to get the average.

Alternative Approach Using Statistics Module

We can also use Python's built-in statistics module for a more readable solution ?

import statistics

def solve_with_statistics(heights):
    unique_heights = set(heights)
    return statistics.mean(unique_heights)

heights = [96, 25, 83, 96, 33, 83, 24, 25]
print("Average using statistics module:", solve_with_statistics(heights))
Average using statistics module: 52.2

Conclusion

Converting a list to a set automatically removes duplicates, making it easy to calculate the average of distinct values. The statistics.mean() function provides an alternative readable approach for computing averages.

Updated on: 2026-03-26T15:34:30+05:30

748 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements