简体   繁体   中英

Python error : AttributeError: 'NoneType' object has no attribute 'len'

My code is very simple but I can't figure out why it is throwing this error ?

def median(numbers):
     newnumbers = numbers.sort()
     length = newnumbers.len()
     print length

median([4,6,1])

I searched online and also on SO and len() is correct way to get length of list. However, I keep getting error "AttributeError: 'NoneType' object has no attribute 'len'"

What am I doing wrong here ? Thanks !

numbers.sort() works in place - it changes numbers, but returns None , so that's what newnumbers contain. You should use newnumbers = sorted(numbers) , and this would solve the exception.

However, please note that sorting isn't required, as you're simply returning the length of the input list. So:

def median(numbers):
    print len(numbers)

would accomplish just the same. (and you're not returning the median)

There are two issues here:

  • The sort() method on lists just modifies the list, without returning a new one, so newnumbers is None .
  • You should write len(newnumbers) , not newnumbers.len() .

The syntax is not correct for finding length of a list.

The only change is len(newnumbers) which is required. There is no sole purpose of sorting which can be seen since you are not displaying the elements, the length will remain same regardless of sorting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM