16

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.

0

2 Answers 2

36

Semantically, this:

print sorted(student_tuples, key=lambda student: student[2])

is the same as this:

def sort_key(student):
    return student[2]

print sorted(student_tuples, key=sort_key)

lambda just provides an alternative syntax for function definition. The result is a function object, just like the one created by def. However, there are certain things that lambda functions 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 key accepts a function, calls it on every value in the sequence passed to sorted, and sorts the values according to the order that their corresponding key values would take if they were sorted themselves.

Sign up to request clarification or add additional context in comments.

Comments

3

lambda is a way to define a function inline, and the part before the colon : is the parameter to the function; in this case it's called student. In this example the function is simply returning the third part of the list or tuple passed to it, which is the age.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.