Full answer
python
students = [("Asha", "B", 88), ("Ben", "A", 75), ("Chen", "B", 92), ("Dara", "A", 75)]
by_marks = sorted(students, key=lambda s: s[2], reverse=True)
print(by_marks)
print(sorted(students, key=lambda s: (s[1], -s[2])))
result = students.sort(key=lambda s: s[0])
print(result, students[0])
print(sorted(["banana", "apple", "Cherry"]), sorted(["banana", "apple", "Cherry"], key=str.lower))Output:
text
[('Chen', 'B', 92), ('Asha', 'B', 88), ('Ben', 'A', 75), ('Dara', 'A', 75)]
[('Ben', 'A', 75), ('Dara', 'A', 75), ('Chen', 'B', 92), ('Asha', 'B', 88)]
None ('Asha', 'B', 88)
['Cherry', 'apple', 'banana'] ['apple', 'banana', 'Cherry']Ben and Dara both have 75, and they keep their original order in by_marks because the sort is stable. The tuple key sorts by section and then by marks descending, using the minus sign for the numeric part. list.sort() returns None, so assigning its result is a common bug. Plain string sorting puts 'Cherry' first because uppercase letters sort before lowercase; key=str.lower gives the case-insensitive order apple, banana, Cherry.
python
students = [("Asha", "B", 88), ("Ben", "A", 75), ("Chen", "B", 92), ("Dara", "A", 75)]
by_marks = sorted(students, key=lambda s: s[2], reverse=True)
print(by_marks)
print(sorted(students, key=lambda s: (s[1], -s[2])))
result = students.sort(key=lambda s: s[0])
print(result, students[0])
print(sorted(["banana", "apple", "Cherry"]), sorted(["banana", "apple", "Cherry"], key=str.lower))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- sorted returns a new list; sort works in place
- key functions define the order
- Sorting is stable
- Tuple keys sort by several fields
- Uppercase sorts before lowercase
Common mistakes
- Writing x = x.sort()
- Using cmp-style functions without functools.cmp_to_key
Follow-ups
- How would you sort descending by a string field and ascending by a number?
- What algorithm does Python use?
Tips
- Mention stability