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.
5. Using sort() We can use the sort() method to sort the set that we obtained in approach 2. This will also remove any duplicates, while preserving the order, but is slower than the dict.
sort() sorts the list and replaces the original list, whereas sorted(list) returns a sorted copy of the list, without changing the original list.
In sorted array, all duplicate elements will be placed adjacent to each other.
The sort() method returns None , which means there is no return value since it just modifies the original list. It does not return a new list.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With