find the median of a list of numbers in python

To find the median of a list of numbers in python, you can use the statistics module. Here's an example:

main.py
import statistics

my_list = [4, 2, 1, 5, 3]  # unsorted list

median = statistics.median(my_list)

print(median)  # output will be 3
134 chars
8 lines

If you prefer to implement the function yourself, you can sort the list and then find the middle element (or elements in case of even-length lists). Here's an example implementation:

main.py
def median(lst):
    sorted_lst = sorted(lst)
    lst_len = len(lst)
    mid = lst_len // 2
    if lst_len % 2 == 0:
        return (sorted_lst[mid - 1] + sorted_lst[mid]) / 2.0
    else:
        return sorted_lst[mid]
219 chars
9 lines

With this implementation, you can find the median of a list by calling median(my_list), where my_list is the list of numbers you want to find the median of.

gistlibby LogSnag