Median : object of type 'NoneType' has no len()


#1



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


I get an error saying "median([1]) resulted in an error: object of type 'NoneType' has no len()". I have tried to google and search, but did not become any wiser. I suspect that it has to do with numbers being counted as empty after numbers=numbers.sort(). I did also try to create a separate list with sorted(numbers), but I got the same error.


def median(numbers):
    numbers=numbers.sort()
    median_value=0
    if len(numbers) == 1:
        median_value=numbers[0]
    elif (len(numbers) % 2) == 1:
        median_value=numbers[len(numbers)/2]
    elif (len(numbers) % 2) == 0:
        median_value=float((numbers[(len(numbers)/2)]+(numbers[(len(numbers)/2)+1]))/2)
    print median_value
    return median_value


#2

sort() will update the list for you, no need to store the result in a variable

actually, sort doesn't return anything, so the default (None) is returned. And None(Type) doesn't have a length.


#3

You will get one more error after solving the None error as @stetim94 mentioned.

In this line of code...
median_value=float((numbers[(len(numbers)/2)]+(numbers[(len(numbers)/2)-1]))/2)

There is difference between these two---

float(5 / 2)
and
float(5) / 3


#4

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