To find the median number of a list in Python, you just need to sort the list of numbers and then find the middle number. If the length of the list is odd, you take the middle number as the median. If the length of the list is even, you find the average between the two most middle numbers.
def findMedian(list_of_numbers):
list_of_numbers.sort()
if len(list_of_numbers) % 2 == 1:
median = list_of_numbers[len(list_of_numbers) // 2]
else:
median = (list_of_numbers[len(list_of_numbers) // 2 - 1] + list_of_numbers[len(list_of_numbers) // 2]) / 2
return median
print(findMedian([9,3,1]))
print(findMedian([10,50,25,30]))
#Output:
3
27.5
When working with lists of numbers in Python, the ability to perform calculations and get certain statistics can be very valuable.
One such calculation and statistic is the median, or middle number, of a collection of data.
In Python, we can easily find the median of a list of numbers with a function.
To find the median of a list of numbers, we first need to sort the list.
Then, depending on if the length of the list is even or odd, we can get the median.
If the length of the given list is odd, we can find the middle index with integer division. If the length of the list is even, then we get the middle two indices with integer division.
Below are some examples of how you can find the median of a list in Python.
def findMedian(list_of_numbers):
list_of_numbers.sort()
if len(list_of_numbers) % 2 == 1:
median = list_of_numbers[len(list_of_numbers) // 2]
else:
median = (list_of_numbers[len(list_of_numbers) // 2 - 1] + list_of_numbers[len(list_of_numbers) // 2]) / 2
return median
print(findMedian([9,3,1]))
print(findMedian([10,50,25,30]))
#Output:
3
27.5
Hopefully this article has been useful for you to learn how to find the median in a list of numbers in Python.