Profile image of Herbcode
Submitted by Herbcode
about 11 years

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

Profile image of ionatan
Submitted by ionatan
about 11 years

1 comments

Profile image of Herbcode
Submitted by Herbcode
over 10 years

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])
Profile image of vinay46242
Submitted by vinay46242
almost 11 years

18 comments

Profile image of QABANBAIBATYR
Submitted by QABANBAIBATYR
almost 11 years

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

Profile image of netPro07681
Submitted by netPro07681
almost 11 years

QABANBAIBATYR, you are absolutely right

Profile image of Ldonovan
Submitted by Ldonovan
almost 11 years

This makes so much sense!! Thanks!!

Profile image of systemRockstar02498
Submitted by systemRockstar02498
almost 11 years

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

Profile image of gigaSolver43830
Submitted by gigaSolver43830
almost 11 years

thanks

Profile image of webjoe
Submitted by webjoe
almost 11 years

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.

Profile image of paynejosh25
Submitted by paynejosh25
almost 11 years

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

Profile image of AlexBunt
Submitted by AlexBunt
almost 11 years

It is not necessary

Profile image of paynejosh25
Submitted by paynejosh25
almost 11 years

ok thx

Profile image of huyafei_
Submitted by huyafei_
almost 11 years

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

Profile image of huyafei_
Submitted by huyafei_
almost 11 years

Oh,I’m sorry, it already work.

Profile image of makowka
Submitted by makowka
over 10 years

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

Profile image of chipBlaster02049
Submitted by chipBlaster02049
over 10 years

Because the index starts from zero.

Profile image of ZenTeapot
Submitted by ZenTeapot
over 10 years

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

Profile image of designAce38978
Submitted by designAce38978
over 10 years

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!

Profile image of Joey_B.
Submitted by Joey_B.
over 10 years

Thanks. Your solution have helped to find my mistake.

Profile image of Hark99
Submitted by Hark99
over 10 years

so simple than i think…thanks

Profile image of egoregorov
Submitted by egoregorov
over 10 years

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])
Profile image of object-whiz-gzjNu
Submitted by object-whiz-gzjNu
over 10 years

1 comments

Profile image of tishahaukongo
Submitted by tishahaukongo
over 10 years

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”]

Profile image of anonymous
Submitted by anonymous
almost 11 years

2 comments

Profile image of -_________-
Submitted by -_________-
almost 11 years

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

Profile image of ZenTeapot
Submitted by ZenTeapot
over 10 years

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)

Profile image of AlexBunt
Submitted by AlexBunt
almost 11 years

2 comments

Profile image of dataAce40013
Submitted by dataAce40013
over 10 years

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.

Profile image of ZenTeapot
Submitted by ZenTeapot
over 10 years

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])

Profile image of shiva.muruka
Submitted by shiva.muruka
over 10 years

Answer 54a36a7e76b8feae040174d7

0 votes

Permalink

I still haven’t fully understood this exercise :/

Profile image of PeppySuperMonkey
Submitted by PeppySuperMonkey
about 11 years

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

Profile image of libeadier
Submitted by libeadier
about 11 years

3 comments

Profile image of chairlord
Submitted by chairlord
about 11 years

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?

Profile image of tephonis
Submitted by tephonis
about 11 years

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!

Profile image of cunzhang
Submitted by cunzhang
almost 11 years

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
Profile image of kris_yu_
Submitted by kris_yu_
almost 11 years

1 comments

Profile image of AlexBunt
Submitted by AlexBunt
over 10 years

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

Profile image of CALEB0
Submitted by CALEB0
almost 11 years

1 comments

Profile image of CALEB0
Submitted by CALEB0
almost 11 years

itz pafect

Answer 54f694459113cb0206000d32

0 votes

Permalink

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

Profile image of harrycaoyu
Submitted by harrycaoyu
almost 11 years

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]

Profile image of linsiwen
Submitted by linsiwen
over 10 years

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?

Profile image of s1008856sms.ed.ac.uk
over 10 years

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.

Profile image of GeorgeNotClooney
Submitted by GeorgeNotClooney
about 11 years

1 comments

Profile image of Mataos
Submitted by Mataos
almost 11 years

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 :)

Profile image of Willmish
Submitted by Willmish
over 10 years

2 comments

Profile image of jover10
Submitted by jover10
over 10 years

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

Profile image of Willmish
Submitted by Willmish
over 10 years

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
Profile image of chipPro75312
Submitted by chipPro75312
over 10 years

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]
Profile image of Kushagra91
Submitted by Kushagra91
over 10 years

1 comments

Profile image of AlexBunt
Submitted by AlexBunt
over 10 years

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)

Profile image of chaoqing
Submitted by chaoqing
over 10 years

1 comments

Profile image of chaoqing
Submitted by chaoqing
over 10 years

哈哈,还是我的简单

Popular free courses

  • In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.
    • Beginner Friendly.
      4 Lessons
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      11 Lessons
  • Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.
    • Beginner Friendly.
      6 Lessons
Explore full catalog