Home > Back-end >  Average of the numbers in a given list
Average of the numbers in a given list

Time:05-20

I have been told to write a function which calculates the average of the numbers in a given list. Empty arrays should return 0. Here is my code:

def find_average(numbers):
    c = sum(numbers)
    for number in numbers:
        d = c / number    
        return d
    pass

Could someone explain why this doesn't work?

CodePudding user response:

The for loop isn't necessary, since you're already using sum(). Once you've summed all the elements, the only thing you need to do is divide the sum by the number of entries in numbers:

def find_average(numbers):
    if not numbers:
        return 0
    return sum(numbers) / len(numbers)

CodePudding user response:

def find_average(numbers):
    c = sum(numbers)
    if not numbers: # to avoid the division by zero
        return 0
    return c / len(numbers)

print(find_average([1, 2, 3]))

When you return it stops the function, so you were only dividing by the first element. To get the number of elements in a list you can use the keyword len.

  • Related