Python Function Practice: Average of a List

Small helper functions are easier to trust when they handle unusual input. An average of an empty list would divide by zero and stop the program. This exercise writes average() with an explicit guard, then tests it on a normal list and on an empty one.

Before you start: Functions, return values, lists and the sum and len built-ins.

Your task

Define average(numbers) so that it returns the mean of a list of numbers, and returns 0 for an empty list. Print the average of scores and of an empty list.

Starter code

scores = [4, 8, 6]

# Define average(numbers). Return 0 for an empty list.
# Then print average(scores) and average([]).

Expected result

6.0
0
Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Check for an empty list first and return 0. Otherwise return sum(numbers) divided by len(numbers).

Show the complete solution and walkthrough
scores = [4, 8, 6]

# Define average(numbers). Return 0 for an empty list.
# Then print average(scores) and average([]).
def average(numbers):
    if not numbers:
        return 0
    return sum(numbers) / len(numbers)

print(average(scores))
print(average([]))
  1. Define def average(numbers): and check if not numbers. An empty list is falsy, so the guard returns 0 immediately.
  2. For other lists, return sum(numbers) / len(numbers). With 4, 8 and 6 the total is 18 and the count is 3.
  3. Print average(scores) and average([]). Python 3 prints 6.0 for the first call because / returns a float, and 0 for the second.

A common mistake

Skipping the guard makes average([]) raise ZeroDivisionError. Printing inside the function instead of returning the value makes the function harder to reuse.

Try an edge case

Decide what an empty input should mean. Returning 0 is a choice; returning None would signal that there is no average, and both are valid if documented.

Take it one step further

Round the result to one decimal place with round(). Then raise a ValueError for non-numeric items instead of failing silently.

Read the python tool guide