Skip to content
← Python for AI/ML · all 50 levels

sorted() with key

Level 40 of 50 · Functions

Level 40 of 50

sorted() with key

sort anything your way. Watch the reel, then work through it below: run the code, take the quiz, keep the cheat sheet.

📒 Open the cheat sheet
SanaWhich food stall is cheapest? Biryani, nihari, or haleem?
TeacherLet Python sort it! And YOU choose what to sort by, with key!
names.py
names = ["Zara", "Ali", "Fatima"]
print(sorted(names, key=len))
TeacherNormally sorted goes A to Z. With key=len, shortest name first!
SanaSo what exactly does key do?
Teacherkey says WHAT to compare! Here, the length of each name.
food.py
food = [("biryani", 350),
        ("nihari", 500),
        ("haleem", 250)]
cheap = sorted(food,
    key=lambda f: f[1])
print(cheap[0])
Teacherkey + lambda? Sort the stalls by price. Haleem wins!

⏸ Pause & predict: what prints?

f = ["kela", "anaar", "seb"]
print(sorted(f, key=len)[0])

Where this leads

Python is step one. Building AI that ships is the rest.

The diploma takes you from zero to deployed computer vision, LLM and agent projects, with engineers who build them for a living. Already code? The bootcamp does it in three months.