Skip to main content

How to find the average of elements in a list in Python

How to find the average of elements in a list in Python.

Here's a step-by-step tutorial on how to find the average of elements in a list using Python.

1: Create a list of numbers

To find the average of elements in a list, you first need to have a list of numbers. You can create a list by assigning a series of numbers to a variable using square brackets. For example:

numbers = [10, 20, 30, 40, 50]

2: Calculate the sum of all elements

To find the average, you need to calculate the sum of all the elements in the list. You can use the built-in sum() function to achieve this. Here's an example:

total = sum(numbers)

3: Determine the number of elements in the list

Next, you need to determine the number of elements in the list. You can use the len() function to get the length of the list. Here's an example:

count = len(numbers)

4: Calculate the average

To find the average, divide the sum of all elements by the number of elements in the list. You can use the division operator / to perform this calculation. Here's an example:

average = total / count

5: Print or use the average value

Finally, you can print the average or use it for further computations. Here's an example of printing the average:

print("The average is:", average)

Alternatively, you can store the average in a variable and use it later in your program.

Complete Example:

Here's a complete example that puts all the steps together:

numbers = [10, 20, 30, 40, 50]
total = sum(numbers)
count = len(numbers)
average = total / count
print("The average is:", average)

Output:

The average is: 30.0

That's it! You now know how to find the average of elements in a list using Python.