Bunny Rabbit Bunny Rabbit - 15 days ago 11
Python Question

Why am I not getting the result of sorted function in expected order?

print activities
activities = sorted(activities,key = lambda item:item[1])
print activities


Activities in this case is a list of tuples like
(start_number,finish_number)
the output of the above code according to me should be the list of values sorted according the the increasing order of
finish_number
. When I tried the above code in shell I got the following output. I am not sure why the second list is not sorted according the the increasing order of the
finish_number
. Please help me in understanding this.

[('1', '4'), ('3', '5'), ('0', '6'), ('5', '7'), ('3', '9'), ('5', '9'), ('6', '10'), ('8', '11'), ('8', '12'), ('2', '14'), ('12', '16')]
[('6', '10'), ('8', '11'), ('8', '12'), ('2', '14'), ('12', '16'), ('1', '4'), ('3', '5'), ('0', '6'), ('5', '7'), ('3', '9'), ('5', '9')]

jro jro
Answer

You are sorting strings instead of integers: in that case, 10 is "smaller" than 4. To sort on integers, convert it to this:

activites = sorted(activities,key = lambda item:int(item[1]))
print activities

Results in:

[('1', '4'), ('3', '5'), ('0', '6'), ('5', '7'), ('3', '9'), ('5', '9'), ('6', '10'), ('8', '11'), ('8', '12'), ('2', '14'), ('12', '16')]
Comments