why is len([1]) giving me a "NoneType" error

220 Views Asked by At

I am currently learning how to code python 2.7 but I have run into a confusing error in the following code which attempts (very inefficiently I assume) to return the median of an input.

def median(lst):

    lst = lst.sort()
    median = 0

    if len(lst) == 1:
        median = lst[0]            
    elif len(lst) % 2 == 0:
        median_sum = lst[len(lst) / 2 - 1] + lst[len(lst) / 2 + 1]
        median = median_sum / 2.0
    else:
        median = lst[len(lst)/ 2 - 1]

    return median

print median([1])

above is my code and it keeps giving me the following error:

Traceback (most recent call last):
  File "C:/Python27/SAVED DOCS/test3.py", line 16, in <module>
    print median([1])
  File "C:/Python27/SAVED DOCS/test3.py", line 6, in median
    if len(lst) == 1:
TypeError: object of type 'NoneType' has no len()

it seems as though it is having an issue with me calling len(lst) where lst = [1] because python seems to think it is a None variable? I'm quite confused.

On the console terminal for python I can type len([1]) and I get a result of 1 without any issue. Also keep in mind I am fully aware this is not the best way to do what I am trying to do but I am just starting to learn python!

Any ideas?

4

There are 4 best solutions below

5
On BEST ANSWER

lst.sort() sorts the list in-place and returns None. So lst = lst.sort() sets lst to None.

I think the best fix is to do

lst = sorted(lst)

This doesn't change the list in-place, so that variables referring to the same list outside of this function are unchanged.

0
On

Your title is mistaken. list.sort() returns None because it operates by side effect; the first line discarded the list.

0
On

Instead of using lst.sort() which returns None, you can use sorted() built-in function like below:

lst = sorted(lst)

Now, lst contains your sorted list.

0
On

think your problem is that lst.sort() returns None.

"TypeError: object of type 'NoneType' has no len()"

see how to solve it here. Why does '.sort()' cause the list to be 'None' in Python?