Confusion regarding sort/sorted


So I already got my code to work (and having now compared it to some others I see that mine is ridiculously bloated). I was just wondering if anyone can explain why sorted works in this case, but trying new = x.sort() does not work. Since what is provided is a list, shouldn't the sort function work? The error I would receive with x.sort() was:

Oops, try again.
median([1]) resulted in an error: object of type 'NoneType' has no len()

I apologize in advanced if this is a stupid question.

def median(x):
    new = sorted(x)
    if len(new) % 2 == 0:    
     c = len(new) / 2 
     e = len(new) / 2 - 1
     d = (new[c] + new[e]) / 2.0
     c = len(new) / 2.0
     e = int(c)
     d = new[e]
    return d


This is not a stupid question at all! It all has to do with how the two functions process the input. Here is an excellent answer I found from soulseekah over on StackExchange ".sort() is in place and returns None, while sorted() creates a brand new sorted list from your list and returns it."

Here is the link to the thread on StackExchange.


Hey, thanks for clarifying that, it was really bugging me. I really appreciate it.


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