0 points Submitted by Herbcode
over 7 years

# sorted(list) versus list.sort()

This code for finding median gives the error message: median() 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)`?

`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

points Submitted by Jonatan
over 7 years Herbcode almost 7 years

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.

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])``````
points Submitted by k v vinay kumar
over 7 years QABANBAIBATYR over 7 years

this one is the most readable and very easy to understand… good job, thanks Nauryzbai Batyr over 7 years

QABANBAIBATYR, you are absolutely right Loriana Nicole Donovan over 7 years

This makes so much sense!! Thanks!! Catherine Click about 7 years

why does it matter if you type in 2.0 vs just 2 at the end of your first return Kylie Shuck about 7 years

thanks Joseph Hsieh about 7 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. paynejosh25 about 7 years

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

It is not necessary paynejosh25 about 7 years

ok thx huyafei_ about 7 years

when n ==1 ,it doesn’t work. huyafei_ about 7 years makowka about 7 years

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

Because the index starts from zero. Matthew Alp almost 7 years

Exactly. The list length is, say, 3, but Python gives the items indexes of [0,1,2]. Bassem Khansa almost 7 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! Joey_B. almost 7 years

Thanks. Your solution have helped to find my mistake. Sudheer Darla almost 7 years

so simple than i think…thanks egoregorov almost 7 years

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

This will also work…

``````import numpy

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

print median([1,2,3,4,5])``````
points almost 7 years tishahaukongo almost 7 years

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

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

points Submitted by Trevor
over 7 years 90 over 7 years

Heh, I felt tempted to hint at that song by Eminem. Matthew Alp almost 7 years

Dammit Texenox.

1 vote

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

points Submitted by AlexBunt Steven Kuipers about 7 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. Matthew Alp almost 7 years

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

1 vote

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

points Submitted by Sethu
over 6 years

I still haven’t fully understood this exercise :/

points Submitted by Daniel Schwartz
over 7 years

## 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

points over 7 years chairlord over 7 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? tephonis over 7 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! cunzhang over 7 years

the upstair is right

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

``````if len(lst) == 1 or len(lst) == 0:
return lst
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``````
points Submitted by kris_yu_
over 7 years AlexBunt almost 7 years

How does this in any way answer the question?

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

points Submitted by CALEB0
over 7 years CALEB0 over 7 years

itz pafect

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

points Submitted by Yu Cao
over 7 years

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, 4, 6, 8]

points Submitted by LINSIWEN
almost 7 years

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?

points almost 7 years

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

if len(new_list)==1: return new_list 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]``````

points Submitted by George Manitsas
over 7 years Mataos about 7 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.

``````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
else:
return result[(ln / 2)]``````

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

points Submitted by Willmish John Overton about 7 years

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

Thanks :)

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``````
points ``````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
else:
return lst[(n - 1) / 2]``````
points Submitted by Kushagra
almost 7 years AlexBunt almost 7 years

How does this in any way answer the question?

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)

points Submitted by chaoqing chaoqing about 7 years