average function python code example

Example 1: average python

import numpy as np
values=[1,10,100]
print(np.mean(values))
values=[1,10,100,np.nan]
print(np.nanmean(values))

Example 2: find average of list python

list = [15, 18, 2, 36, 12, 78, 5, 6, 9]

# for older versions of python
average_method_one = sum(list) / len(list) 
# for python 2 convert len to a float to get float division
average_method_two = sum(list) / float(len(list))

# round answers using round() or ceil()
print(average_method_one)
print(average_method_two)

Example 3: python average

# Using statistics package to find average
import statistics as st

my_list = [9, 3, 1, 5, 88, 22, 99]
print(st.mean(my_list))

Example 4: python average

def avrg(values): # where values is a list of all values
  return sum(values)/len(values)

Example 5: how to use a function to find the average in python

avreage_cost = cost
    avg = sum(avreage)/len(avreage) 
    print("The average amout you spent is ", round(avg,2))

Example 6: calcutalte average python

# app.py

def averageOfList(num):
    sumOfNumbers = 0
    for t in num:
        sumOfNumbers = sumOfNumbers + t

    avg = sumOfNumbers / len(num)
    return avg


print("The average of List is", averageOfList([19, 21, 46, 11, 18]))