Possible Duplicate:
Syntax behind sorted(key=lambda 🙂
I was going through the documentation and came across this example:
> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10), ]
> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
What I don’t understand is what are lambda and student here? Can they be replaced by any other names? And what the : do in student:student[2]? It’s a little ambiguous since I’ve never come across this before.
Semantically, this:
is the same as this:
lambdajust provides an alternative syntax for function definition. The result is a function object, just like the one created bydef. However, there are certain things thatlambdafunctions can’t do — like defining new variables. They’re good (depending on who you ask) for creating small one-use functions, such as this one.Once you understand that, then all you have to know is that
keyaccepts a function, calls it on every value in the sequence passed tosorted, and sorts the values according to the order that their correspondingkeyvalues would take if they were sorted themselves.