Median, NoneType Error


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#


I get the error: "Oops, try again. median([1]) resulted in an error: object of type 'NoneType' has no len()" but don't know how to fix this.


def median(lst):
    lst = lst.sort()
    if len(lst) % 2 == 0:
        return (lst[len(lst) / 2] + lst[len(lst) / 2 + 1]) / 2.0
    else:
        return lst[len(lst) / 2]


#2

The list.sort() method has no return value, so lst will be None.

>>> lst = [1,2,3,4,5]
>>> lst = lst.sort()
>>> print (lst)
None
>>>

To make a sorted copy of the original list, use sorted()

sorted_list = sorted(lst)

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.