Editor

Add Type Hints to a Function

Intermediate · Write the code · from Python Type Hints: Add Types, Generics, and the typing Module

From the lesson: How Do You Add Type Hints to Variables and Functions?

The syntax is simple. For variables, add a colon and the type after the name. For functions, annotate each parameter and use -> for the return type.

Read this part of the lesson

Add proper type hints to this function and its variables. The function takes a list of integers and returns their average as a float. Also add type hints to the two variables.

Make the function work correctly, then print the result for the list [10, 20, 30, 40].

# Add type hints to the function signature and variables
def average(numbers):
total = sum(numbers)
count = len(numbers)
return total / count
result = average([10, 20, 30, 40])
print(result)

More Type Hints exercises

All Python exercises · 50 practice problems · Advanced Python quiz