Skip to main content

How to calculate the average of a list of numbers in Python

How to calculate the average of a list of numbers in Python.

Here's a step-by-step tutorial on how to calculate the average of a list of numbers in Python:

Step 1: Create a list of numbers

  • Start by creating a list of numbers that you want to calculate the average for. For example, let's say we have a list called numbers which contains the following numbers: [5, 10, 15, 20, 25].

Step 2: Calculate the sum of the numbers

  • To calculate the sum of the numbers in the list, we can use the built-in sum() function in Python. The sum() function takes an iterable (such as a list) as its argument and returns the sum of all the elements. In this case, we can use sum(numbers) to calculate the sum of the numbers in our numbers list.

Step 3: Calculate the length of the list

  • To calculate the average, we also need to know how many numbers are in the list. We can use the built-in len() function in Python to get the length of the list. For example, len(numbers) will return 5 in our case.

Step 4: Calculate the average

  • To calculate the average, divide the sum of the numbers by the length of the list. We can use the division operator / in Python to perform this calculation. For example, average = sum(numbers) / len(numbers) will give us the average.

Step 5: Print the average

  • Finally, you can print the average to see the result. You can use the print() function in Python to display the value of the average. For example, print(average) will print the average to the console.

Here's an example code snippet that puts all the steps together:

# Step 1: Create a list of numbers
numbers = [5, 10, 15, 20, 25]

# Step 2: Calculate the sum of the numbers
total = sum(numbers)

# Step 3: Calculate the length of the list
length = len(numbers)

# Step 4: Calculate the average
average = total / length

# Step 5: Print the average
print(average)

Output:

15.0

In this example, the average of the numbers [5, 10, 15, 20, 25] is 15.0.

You can modify the numbers list with your own set of numbers to calculate the average for any list of numbers you want.