How can I create a function to find the average of a list?

636 views Asked by At

I'm trying to create a functional for the average of a list that accepts three parameters: a mandatory list of numbers, an optional minimum value which defaults to zero, and an an optional maximum value which defaults to 100. The function should only calculate the average of values between the stated minimum and maximum, even if there are other vaues in the list.

def avgList(lst, low = 0, high = 100):
    """Calculates the average of a list of values"""
    for i in range(low, high):
        avg = sum(lst)/len(lst)
        return avg

This is what I tried. I also have a few sample outputs I tried, it worked for the first two but not for the third. The first is asking for the mean of a list from 1 to 10

lst1 = list(range(1,11))
average1 = avglist(lst1)
average1

The second is asking for the mean of the numbers between 20 and 80 in a list from 1 to 100.

lst2 = list(range(1, 101))
average2 = avglist(lst2, 19, 80)
average2

The third is asking for a mean of all the numbers between 30 and 100 in a randomly generated list of 100 numbers between 1 and 100. I would expect the mean to be around 65, but it usually ends up around 50

lst3 = [] 
for i in range(1, 100):   
    n = random.randint(1, 100)   
    lst3.append(n) 
average3 = avglist(lst3, 29, 100)
average3
3

There are 3 answers

2
JNevill On

Your for i in range(low,high) really doesn't make any sense. Inside that loop it calculates the average for the full lst and immediately returns the first result (the first time it hits return on the first iteration, it does so and the function ends).

Instead, rebuild your list and reject any elements that fall outside of your low/high bounds, then take the average of that:

def avgList(lst, low = 0, high = 100):
    """Calculates the average of a list of values"""
    truncated_list = [x for x in lst if (x>low and x<high)]    
    avg = sum(truncated_list)/len(truncated_list)
    return avg
1
azro On

Your code does not do what you want at all, you do not filter the values from lst at all, there is point at iterating on the range from low to high


What you want is

def avgList(lst, low = 0, high = 100):
    """Calculates the average of a list of values"""
    valid_values = [x for x in lst if low <= x <= high]
    return sum(valid_values) / len(valid_values)
0
Heineken On
.... The function should only calculate the average of values between the stated minimum and maximum, even if there are other vaues in the list.

You can declare two variables, one that keeps count and one for the sum. Then just loop through the list of numbers and only take in account those numbers that fit your criteria:

def avgList(nums: list, low: int, high: int):
    sum = 0
    counter = 0
    for n in nums:
        if n >= low and n <= high:
            sum += n
            counter += 1
    
    return sum/counter