The median of a set of values is a useful statistical measurement that shows the middle value when arranged in ascending order.
Python provides built-in functions to sort an array, which can then be used to find the median. However, in this tutorial, we will learn how to find the median in Python without using any sorting function.
Step 1: Understanding the Median
The median is either the middle element in an odd-numbered array or the average of the middle two elements in an even-numbered array. We want to achieve this in Python without using external library methods for sorting data.
Step 2: Writing a Function to Find the Median
This code defines a function that sorts the input list, calculates the median based on whether the number of elements is even or odd, and returns the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
def find_median(numbers): # First, we sort the list in ascending order. numbers.sort() # Calculate the length of the list. n = len(numbers) # Check if the list is empty. if n == 0: return "List is empty" # If the number of elements is odd, return the middle element. if n % 2 != 0: middle_index = n // 2 median = numbers[middle_index] else: # If the number of elements is even, return the average of the two middle elements. middle_index_1 = n // 2 middle_index_2 = middle_index_1 - 1 median = (numbers[middle_index_1] + numbers[middle_index_2]) / 2.0 return median |
Step 3: Testing Our Function
Next, we’ll test our function using an example list: [1, 3, 3, 6, 7, 8, 9]
1 |
print(find_median([1, 3, 3, 6, 7, 8, 9])) |
We’ll also test it with an even amount of numbers: [1, 2, 3, 4]
1 |
print(find_median([1, 2, 3, 4])) |
6.0 2.5
Conclusion
This guide demonstrated how to find the median value of a list in Python, without using a sorting function. We created a custom function, find_median, to implement the necessary logic.
By progressively reducing the list to a smaller section around the geographic mean, we were able to approximate the median. This demonstration not only exemplified the concept of median but also highlighted Python’s flexibility in data manipulation.