Search⌘ K

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

Explore how to calculate the mean, median, and mode of a list in Python. Understand sorting, counting occurrences, and handling list elements to determine these central tendency measures accurately. This lesson provides clear steps to analyze list data with practical code examples.

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

Python 3.8
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
...