Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sorted() in Python [duplicate]

Tags:

python

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.

like image 352
Programming Noob Avatar asked Oct 09 '12 02:10

Programming Noob


People also ask

Does sorted () remove duplicates?

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.

Does Python sorted make a copy?

sort() sorts the list and replaces the original list, whereas sorted(list) returns a sorted copy of the list, without changing the original list.

Can a sorted array have duplicates?

In sorted array, all duplicate elements will be placed adjacent to each other.

Does sort () Create a new list?

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.


2 Answers

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.

like image 200
senderle Avatar answered Oct 21 '22 21:10

senderle


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.

like image 3
Mark Ransom Avatar answered Oct 21 '22 19:10

Mark Ransom