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?
lst.sort()
sorts the list in-place and returnsNone
. Solst = lst.sort()
setslst
toNone
.I think the best fix is to do
This doesn't change the list in-place, so that variables referring to the same list outside of this function are unchanged.