Delete Icon
This forum is now read-only. Please use our new forums at discuss.codecademy.com.
0 points
Submitted by Herbcode
6 years ago

sorted(list) versus list.sort()

This code for finding median gives the error message: median([1]) resulted in an error: object of type ‘NoneType’ has no len()

def median(ListIn):
    ListIn = ListIn.sort()
    n = len(ListIn)
    if n % 2 == 0:
        return (ListIn[n/2-1] + ListIn[n/2])/2.0
    else:
        return ListIn[(n-1)/2]

But why does it work when ListIn = ListIn.sort() is replaced with ListIn = sorted(ListIn)?

Answer 548e5f1f86f5521305007e9d

55 votes
Best answer

Permalink

list.sort and sorted are different objects, they do different things both are callable, one is a method and the other is a function since they behave differently you will have to use them differently, even if their purposes are largely the same

list.sort has no return value, instead it has the side effect that the instance of list that it was called on will be sorted after the method has finished

sorted leaves the argument unchanged and instead creates and returns a list consisting of the same elements as the argument that you passed to it

you can look them up in python’s documentation, or you can call the function help:

help(sorted)
help(list.sort)

output:

Help on built-in function sorted in module __builtin__:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

basically says it takes one argument that you have to supply and then a couple of optional ones, you’d have to look them up for what those optional ones do

-

Help on method_descriptor:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1

only optional arguments, and they are the same as that of sorted, cmp, key and reverse - you can probably guess what the reverse one does, the others need to be looked up

documentation for sorted: https://docs.python.org/2/library/functions.html#sorted list.sort: https://docs.python.org/2/tutorial/datastructures.html#more-on-lists (it happens to refer to the documentation of sorted for the full documentation)

the 2 in the url’s can be changed to 3 for python 3 documentation. notably sorted will not return a list, it instead returns an iterable (an object that will yield values when you ask for it, but until you do it does not get evaluated. for example, xrange(1000000) doesn’t make a list of a million integers, instead it gives you one integer at a time and computes the next one each time you ask for it - this is called lazy evaluation

1751 points
Submitted by Jonatan
6 years ago

1 comments

Herbcode 5 years ago

Thanks for your explanation; it’s way more helpful than Python’s documentation.

In short, list.sort() sorts the given list, but sorted(list) does not modify that list – it only returns a sorted copy of that list.

Answer 54f8952f51b8875ecc005c3f

36 votes

Permalink

This is mine, works fine::

def median(lists):
    lists = sorted(lists)
    n = len(lists)
    if n % 2 == 0:
         return (lists[n/2-1] + lists[n/2])/2.0
    else:
        return lists[(n/2)]

print median([1, 2, 4])
278 points
Submitted by k v vinay kumar
6 years ago

18 comments

QABANBAIBATYR 6 years ago

this one is the most readable and very easy to understand… good job, thanks

Nauryzbai Batyr 5 years ago

QABANBAIBATYR, you are absolutely right

This makes so much sense!! Thanks!!

Catherine Click 5 years ago

why does it matter if you type in 2.0 vs just 2 at the end of your first return

Kylie Shuck 5 years ago

thanks

Joseph Hsieh 5 years ago

2.0 casts the results as a float (has decimals). Another way you can do it is wrap the entire argument with float() to cast.

paynejosh25 5 years ago

why did you, in the else statement put brackets inside the list lists[(n/2)] does it matter if you put them there

AlexBunt 5 years ago

It is not necessary

paynejosh25 5 years ago

ok thx

huyafei_ 5 years ago

when n ==1 ,it doesn’t work.

huyafei_ 5 years ago

Oh,I’m sorry, it already work.

makowka 5 years ago

can someone explain why there is -1 in the first return line? i know it works, but shouldn’t it be plus..

黃泓溥 5 years ago

Because the index starts from zero.

Matthew Alp 5 years ago

Exactly. The list length is, say, 3, but Python gives the items indexes of [0,1,2].

Bassem Khansa 5 years ago

what if the length of the list is odd (“let’s say 5”) , how comes it’s possible to divide odd over 2===> 5/2 to get the index of the median! that doesn’t make sense to me! help please!

Joey_B. 5 years ago

Thanks. Your solution have helped to find my mistake.

Sudheer Darla 5 years ago

so simple than i think…thanks

egoregorov 5 years ago

Bassam i think because its not a float the program reads 5/2 as 2, not 2.5

Answer 55b711b276b8fe3c230007dd

3 votes

Permalink

This will also work…

import numpy

def median(list):
      return numpy.median(list)

print median([1,2,3,4,5])
1773 points
Submitted by Alvin Padayachee
5 years ago

1 comments

tishahaukongo 5 years ago

Simplest code I’ve seen for this exercise,and it works.

Answer 54e2712976b8feb615000917

2 votes

Permalink

Well, say list = [“Hi”, “my name”, “is James”] if you say sorted(list) then it takes the sorted list as an argument, but doesn’t actually do anything to the list, if you print it it will give [“Hi”, “my name”, “is James”], but if you do list.sort() then print the list, it will give [“Hi”, “is James”, “my name”]

754 points
Submitted by Trevor
6 years ago

2 comments

90 6 years ago

Heh, I felt tempted to hint at that song by Eminem.

Matthew Alp 5 years ago

Dammit Texenox.

Answer 55362486d3292f5eda00012c

1 vote

Permalink

list.sort() rearranges the list. sorted(list) has to be assigned. i.e. sorted_list = sorted(unsorted_list)

943 points
Submitted by AlexBunt
5 years ago

2 comments

Steven Kuipers 5 years ago

Yeah this took me a while to figure out because if you just write down sorted(x) in your function it doesn’t produce an error.

Matthew Alp 5 years ago

Yeah, you have to say something such as myList=sorted(myList) or another line with the same meaning.

Answer 5614a7b4e39efe53a200025e

1 vote

Permalink

def median(list_name1):
list_name=sorted(list_name1)
size=len(list_name)
if size%2==0:
    a=list_name[size/2]
    b=list_name[(size/2)-1]
    return (a+b)/2.0

else:
    c=list_name[size/2]
    return c        

median([7,12,3,1,6,4,7,8])

360 points
Submitted by Sethu
5 years ago

Answer 54a36a7e76b8feae040174d7

0 votes

Permalink

I still haven’t fully understood this exercise :/

234 points
Submitted by Daniel Schwartz
6 years ago

Answer 54b7929d76b8fe804c001cc4

0 votes

Permalink

Here is my code that works 100%

def median(lst): srtlst=sorted(lst) if len(srtlst)%2!=0: return srtlst[int(len(srtlst)/2+0.5)] else: return (srtlst[len(srtlst)/2]+srtlst[len(srtlst)/2-1])/2.0

302 points
Submitted by libeadier
6 years ago

3 comments

chairlord 6 years ago

So I get why this works, and it’s a very neat piece of code, but the part I get is why does;

return srtlst[int(len(srtlst)/2+0.5)]

work? Does the addition of the 0.5 automatically make the division result into a float? I thought this would return an integer and then convert to a float once you add on the 0.5?

tephonis 6 years ago

The +0.5 is completely erroneous as the float is immediately converted back to an integer by the int() function included in the line. Without the int() function, however, an error would be returned since list indices must be integers and not floats. Better would be “return srtlst[len(srtlst)/2]”

My guess is that libeadier was thinking if he divided an odd list length by 2 he would always have 0.5 remaining and needed to correct for this. For an entry=[1, 2, 3, 4, 5], one would think that len(entry)/2 would return 2.5. However, the len() function is an integer, so it will return 2 instead of 2.5. This is fine though since we WANT index 2 and not 3 as I suspect libeadier was trying to get. You have to remember that lists begin counting at 0!

cunzhang 6 years ago

the upstair is right

Answer 54e1d5c8d3292fcb3a001668

0 votes

Permalink

def median(lst): lst = sorted(lst)

if len(lst) == 1 or len(lst) == 0:
    return lst[0]
elif len(lst) > 1 and len(lst) % 2 == 0:
    median = (lst[len(lst) / 2] + 
              lst[len(lst) / 2 - 1]) / 2.0
    return median
else:
    median = lst[(len(lst) - 1) / 2]
    return median
433 points
Submitted by kris_yu_
6 years ago

1 comments

AlexBunt 5 years ago

How does this in any way answer the question?

Answer 54e3651a51b887b23a002457

0 votes

Permalink

def median(lst): srtlst=sorted(lst) if len(srtlst)%2!=0: return srtlst[int(len(srtlst)/2+0.5)] else: return (srtlst[len(srtlst)/2]+srtlst[len(srtlst)/2-1])/2.0

271 points
Submitted by CALEB0
6 years ago

1 comments

CALEB0 6 years ago

itz pafect

Answer 54f694459113cb0206000d32

0 votes

Permalink

list.sort( ) gives out the same result as sorted(list) does in this case

433 points
Submitted by Yu Cao
6 years ago

Answer 55d4164193767600490004f5

0 votes

Permalink

CODE: def purify(num): a = [] for i in num: if i % 2 == 0: a.append(i) return a print purify([1,2,3]) print purify([1,2,3,4,5,6,7,8,9])

RUNNING RESULT: [2] [2, 4, 6, 8]

278 points
Submitted by LINSIWEN
5 years ago

Answer 55d8c11ad3292fe43a0000f2

0 votes

Permalink

Why is it necessary to have the decimal point for 2.0 in line five? I have a feeling this was covered before but I can’t remember. It doesn’t work with just 2, why is this?

278 points
5 years ago

Answer 54d1fbb951b8877af6001c2a

-1 votes

Permalink

def median(the_list): new_list=sorted(the_list) middle_number= len(new_list)/2

if len(new_list)==1: return new_list[0] else: if len(new_list)%2==0:

        return (new_list[middle_number-1]+new_list[middle_number])/2.0

    else:

        return new_list[middle_number]

Basicaly mine answer doesn’t add anything except “readability” which counts and helps in programming.

290 points
Submitted by George Manitsas
6 years ago

1 comments

Mataos 5 years ago

You don’t need that first if statement, If len(newlist) == 1 then the calculations performed below will still come up with the correct median.

However, your code does not work with an empty list, it’ll show an error, so you might want to make your first if statement: if len(newlist == 0: return 0

Also make sure are your variables are typed the same. The variable newlist sometimes appears as new_list and middlenumber sometimes appears as middle_number.

Answer 55630acd9113cba3190004a9

-1 votes

Permalink

def median(listn):
result = sorted(listn)
ln = len(result)
if ln % 2 == 0:
    return (result[ln/2 - 1] + result[ln/2])/2.0
elif len(result) == 1:
    return result[0]
else:
    return result[(ln / 2)]

If you see something that’s incorrect or something that can be shorter pls commen :)

928 points
Submitted by Willmish
5 years ago

2 comments

John Overton 5 years ago

You could cut out the elif lines completely and the code will still run the same way.

Willmish 5 years ago

Thanks :)

Answer 5569749576b8fe8d4200015d

-1 votes

Permalink

Thats my 8-lines of code that worked well

def median(lista):
new_list = sorted(lista)
odd_avg = new_list[(len(new_list) - 1)/2]
even_avg = (new_list[(len(new_list)/2)] + new_list[((len(new_list)/2) - 1)]) / 2.0
if len(new_list) % 2 == 0:
    return even_avg
else:
    return odd_avg
1006 points
Submitted by Shady El Shafei
5 years ago

Answer 559e7c86937676c0c700020d

-1 votes

Permalink

def median(lst):
lst = sorted(lst)
n = len(lst)
if n % 2 == 0:
    x = lst[n / 2]
    y = lst[(n / 2) - 1]
    return ((x + y) / 2.0)
elif n == 1:
    return lst[0]
else:
    return lst[(n - 1) / 2]
722 points
Submitted by Kushagra
5 years ago

1 comments

AlexBunt 5 years ago

How does this in any way answer the question?

Answer 556fce1ee39efe82ce000a72

-3 votes

Permalink

def purify(numbers): b=[] for i in range(0,len(numbers)): if numbers[i]%2==0: b.append(numbers[i]) return b

a=[4,5,5,4,6,7,8,9,10,11,11,12] print purify(a)

332 points
Submitted by chaoqing
5 years ago

1 comments

chaoqing 5 years ago

哈哈,还是我的简单