Finding median

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/median?action=resume_content_item

In the following codes for looking for median of a numerical list:
def median(list):
sorted_list = sorted(list)
if len(sorted_list) % 2 != 0:
index = len(sorted_list) // 2
return sorted_list[index]
elif len(sorted_list) % 2 == 0:
index_1 = len(sorted_list) / 2
index_2 = len(sorted_list) / 2 - 1
median = (sorted_list[index_1] + sorted_list[index_2]) / 2.0
return median

print median([2, 3, 4, 5, 6, 8, 7, 9])

Why is the " index_2 = len(sorted_list) / 2 - 1" not " index_2 = len(sorted_list) / 2 + 1 "?

lets say you have a list with 6 items (so length 6)

then the indices are: 0, 1, 2, 3, 4, 5

so the middle two values reside at index 2 and 3.

6 / 2 = 3, which is the right middle index

so 6 / 2 - 1 = 2, which is the left middle index

you can try the math for lists of other length as well (8, 10 and so on), you will always need length / 2 and length / 2 - 1

1 Like

Thank you! It helped!

1 Like