how to find median of list in python code example
Example 1: how to get median mode average of a python list
>>> import statistics
>>> statistics.median([3, 5, 1, 4, 2])
3
>>> statistics.median([3, 5, 1, 4, 2, 6])
3.5
Example 2: finding median on python
def calculate_median(n):
N = len(n)
n.sort()
if N % 2 == 0:
m1 = N / 2
m2 = (N / 2) + 1
m1 = int(m1) - 1
m2 = int(m2) - 1
median = (n[m1] + n[m2]) / 2
else:
m = (N + 1) / 2
m = int(m) - 1
median = n[m]
return median
Example 3: find the median of input number in a list and print
import statistics
array = []
n = int(input())
for _ in range(n):
array.append(int(input()))
print (int(statistics.median(array)))