-4

I have a doubt in the following code like i just want to know how the

 a.sort(key= lambda marks: marks[1])

function able to shot and return the nested list again. can any explain this ?

 n=int(raw_input())
    a=[]
    for i in range(n):
        s=raw_input()
        v=float(raw_input())
        a.append([s,v])
    a.sort(key= lambda marks: marks[1])
    print a
3
  • sort sorts its elements. The key function serves to identify what to sort by. Which part is unclear? What lambda is? How sort works?...
    – Amadan
    Oct 16, 2015 at 2:15
  • here a is the nested list right ? .. So normally sorting with numbers are easy to understand .. i want to know about the nested list shorting .
    – Bee..
    Oct 16, 2015 at 2:23
  • It's just sorting, like any other. The main point is to know when one element is bigger or smaller than another, which is obvious for numbers; but here, we want to sort by the second element, and that's what key gives us.
    – Amadan
    Oct 16, 2015 at 2:27

1 Answer 1

2
a.sort(key= lambda marks: marks[1])

This is equivalent to:

def getOneth(marks):
    return marks[1]

a.sort(k=getOneth)

The idea is that a is a list of indexable things. a will be sorted by the value of the second thing in each element

EDIT: How lambda in sort works

When you want to sort a list of things, say from smallest to biggest, you need to evaluate each thing. Only when you do such evaluation, will you be able to decide which thing goes before/after which other thing

Now, let's say you have a list of numbers that you want to sort from smallest to largest. Well, that's easy - the value of a number is immediately obvious. But let's say you want to sort a group of people - you could sort this group by the height of each person, or by their name, or by any other measurable attribute. Thus, when you have a list of such people, you need to tell sort that you will use such an attribute. The key attribute allows you to do this, by specifying a function. The function will be used by sort on each element in the list, to figure out the element's value. Thus the function necessarily expects one input parameter and returns something descriptive of that input's value. Since we don't how how and when sort is going to evaluate each list element, we simply provide the name of the function that it can later call as required

2
  • we have to pass some argument in "a.sort(k=getOneth)" right ? .. this is not clear to me ..can you please explain that ?
    – Bee..
    Oct 16, 2015 at 2:26
  • @Bee..: check out the edit Oct 16, 2015 at 2:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.