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