[Tutor] medians

Don Arnold Don Arnold" <darnold02@sprynet.com
Thu Jan 2 11:58:02 2003


> On Thu, 2 Jan 2003, Thomi Richards wrote:
>
> >
> > I think I'm missing something in the manual, but:
> >
> > what's the easiest way to find the median from a list of numbers? I'm
> > sure there is something really obvious, but I'm too tired to think right
> > now,
>
> I don't believe there is a special function in the library for this little
> task. Well, the median is (if I remember correctly) the value of the index
> in the middle postion of a sorted list.
>
> list_of_numbers.sort() # sort in place..
> median = list_of_numbers[(len(list_of_numbers)-1)/ 2 ]
>
> would do it.
>

Actually, this is correct if the list has an odd number of elements. If the
list has an even number of elements, the median is the average of the middle
two elements.

def median(aList):
    tempList = aList[:]
    tempList.sort()
    listLen = len(tempList)
    middleIndex = (listLen - 1) / 2
    if listLen % 2 == 1:
        #odd number of elements. return middle element
        return tempList[middleIndex]
    else:
        #even number of element. return average of middle 2 elements
        return (tempList[middleIndex] + tempList[middleIndex + 1]) / 2.0

if __name__ == '__main__':
    theList = [2,3,4,5,6]
    print theList
    print 'median = ', median(theList)

    theList = [1,2,6,7]
    print theList
    print 'median = ', median(theList)


>>>
[2, 3, 4, 5, 6]
median =  4
[1, 2, 6, 7]
median =  4.0

HTH,
Don