You're not accumulating anything; you're replacing total
with a new value each time through the loop. So, at the end of the loop, total
is the value from the last element of lst
. A sorted list and an unsorted list will generally have different last elements.
What you probably wanted is:
total += abs(med - i)
Or, more simply, replace the whole function with:
total = sum(abs(med-i) for i in lst)