Confusion regarding sort/sorted


#1


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

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
    else:
     c = len(new) / 2.0
     e = int(c)
     d = new[e]
    return d


#2

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.


#3

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


#4

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