how to average a list in python
how to average a list in python
To average a list of numbers in Python, you can use the built-in sum()
and len()
functions. Here’s an example:
my_list = [10, 20, 30, 40, 50]
average = sum(my_list) / len(my_list)
print(average)
This will output:
30.0
In this example, sum(my_list)
calculates the sum of all the numbers in the list, and len(my_list)
gets the length of the list. Dividing the sum by the length gives the average value of the list.
Note that a result is a floating-point number, even if all the numbers in the list are integers. If you want to round the average to a certain number of decimal places, you can use the round()
function:
my_list = [10, 20, 30, 40, 50]
average = sum(my_list) / len(my_list)
rounded_average = round(average, 2)
print(rounded_average)
This will output:
30.0
Here, rounded_average
is the average value rounded to 2 decimal places.