Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

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 lambda can hold only one expression (no if blocks, loops or return). PEP 8 says do not store one in a name (area = lambda r: ...); use def 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.

Search the guide