...

/

Solution: Calculate the Mean, Median, and Mode of a List

Solution: Calculate the Mean, Median, and Mode of a List

Learn how to calculate the mean, median, and mode of elements in a list.

We'll cover the following...

The solution to the problem of calculating the mean, median, and mode of elements in a list is given below.

Solution

Press + to interact
lst = [10, 20, 30, 40, 30, 60, 70, 30, 80, 30]
# Mean
n = len(lst)
lst_sum = sum(lst)
mean = lst_sum / n
# Median
n = len(lst)
lst.sort()
if n % 2 == 0 :
median1 = lst[ n // 2]
median2 = lst[n // 2 - 1]
median = ( median1 + median2 ) / 2
else :
median = lst[ n // 2 ]
# Mode
lst1 = [0, 0]
for num in lst :
occ = lst.count(num)
if occ > lst1[0] :
lst1 = [occ, num]
print('List =', lst)
print('Mean =', mean)
print('Median =', median)
print('Mode =', lst1[1])

Explanation

  • Lines 3–5: We get the length of the list lst and store it in
...