How to Find the Median in Python Without a Sorting Function

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.

Step 3: Testing Our Function

Next, we’ll test our function using an example list: [1, 3, 3, 6, 7, 8, 9]

We’ll also test it with an even amount of numbers: [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.