Part 05 / Topic 6 of 9
lambda: small one-line functions
lambda args: expression makes a tiny function without a name. Use it for short, throw-away logic, mostly as key= in sorted, min, max.
Real-world example: sort students by marks.
students = [("Asha", 82), ("Ravi", 91), ("Meera", 76)]
by_marks = sorted(students, key=lambda s: s[1], reverse=True)
print(by_marks) # [('Ravi', 91), ('Asha', 82), ('Meera', 76)]
topper = max(students, key=lambda s: s[1])
print(topper[0]) # Ravi
If the logic needs more than one line, write a normal def instead.
๐ Going deeper: a
lambdacan hold only one expression (noifblocks, loops orreturn). PEP 8 says do not store one in a name (area = lambda r: ...); usedef area(r):so errors show a real name.
Done here? The practice set for Part 5 โ 8 exercises with solutions โ is on the part page.