Lesson 25 of 34

lambda, sorted() and key

9 min 30 XP

A lambda is a tiny one-line function. lambda x: x * 2 is the same as def double(x): return x * 2.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

sorted(list, key=...) lets you choose what to sort by. reverse=True sorts from largest to smallest.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

sorted() returns a new list and leaves the original alone. list.sort() changes the list itself.

Challenge

+30 XP

students = [("Arun", 80), ("Priya", 95), ("Kavi", 70), ("Ravi", 88)]. Sort them with the highest marks first and print only the names, one per line.

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.