Python – Average of digit greater than K

When it is required to find the average of numbers greater than K in a list, we can use iteration to filter elements and calculate the mean. This involves counting qualifying elements and summing their values.

Example

my_list = [11, 17, 25, 16, 23, 18]
print("The list is :")
print(my_list)

K = 15
print("The value of K is")
print(K)

my_sum = 0
my_count = 0

for number in my_list:
    if number > K:
        my_sum += number
        my_count += 1

if my_count > 0:
    average = my_sum / my_count
    print("The average of numbers greater than K is :")
    print(average)
else:
    print("No numbers greater than K found")

Output

The list is :
[11, 17, 25, 16, 23, 18]
The value of K is
15
The average of numbers greater than K is :
19.8

Using List Comprehension

A more concise approach using list comprehension and built-in functions ?

my_list = [11, 17, 25, 16, 23, 18]
K = 15

filtered_numbers = [num for num in my_list if num > K]
print("Numbers greater than K:", filtered_numbers)

if filtered_numbers:
    average = sum(filtered_numbers) / len(filtered_numbers)
    print("Average:", average)
else:
    print("No numbers greater than K found")
Numbers greater than K: [17, 25, 16, 23, 18]
Average: 19.8

Explanation

  • A list is defined containing sample numbers

  • The threshold value K is set to 15

  • The list is iterated to find numbers greater than K

  • Both sum and count are tracked for average calculation

  • The average is calculated as sum divided by count

  • A check ensures division by zero is avoided

Conclusion

Use iteration with sum and count tracking to find the average of filtered numbers. List comprehension provides a more Pythonic approach for the same task.

Updated on: 2026-03-26T01:12:03+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements