🔹 1. Sort strings by last character
strings = ["apple", "banana", "pear", "kiwi"]
sorted(strings, key=lambda s: s[-1])
# ['banana', 'pear', 'apple', 'kiwi'] (sorted by last letter)
🔹 2. Sort numbers by absolute value
nums = [-10, -2, 3, 5, -7]
sorted(nums, key=lambda x: abs(x))
# [-2, 3, 5, -7, -10]
🔹 3. Sort tuples by the 2nd element
pairs = [(1, "b"), (3, "a"), (2, "c")]
sorted(pairs, key=lambda x: x[1])
# [(3, 'a'), (1, 'b'), (2, 'c')]
🔹 4. Sort tuples by multiple fields (first by name, then by score)
students = [("Alice", 85), ("Bob", 75), ("Alice", 90)]
sorted(students, key=lambda x: (x[0], x[1]))
# [('Alice', 85), ('Alice', 90), ('Bob', 75)]
🔹 5. Sort by length, then alphabetically
words = ["pear", "apple", "fig", "banana"]
sorted(words, key=lambda w: (len(w), w))
# ['fig', 'pear', 'apple', 'banana']
🔹 6. Sort case-insensitively
names = ["bob", "Alice", "carol"]
sorted(names, key=lambda s: s.lower())
# ['Alice', 'bob', 'carol']
🔹 7. Sort dictionary items by value
scores = {"Alice": 90, "Bob": 75, "Carol": 85}
sorted(scores.items(), key=lambda x: x[1], reverse=True)
# [('Alice', 90), ('Carol', 85), ('Bob', 75)]
✅ Patterns to remember
lambda x: x[-1]
→ last element/character
lambda x: abs(x)
→ absolute value
lambda x: x[n]
→ nth element of tuple/list
lambda x: (condition1, condition2)
→ multi-level sort
lambda x: x.lower()
→ case-insensitive