Sort a List of Tuples by Second Value

Medium ⏱ 12 min 48% acceptance ★★★★★ 4.5
Write sort_by_score(records) where records is a list of (name, score) tuples. Return the list sorted by score descending; if scores tie, sort those names alphabetically ascending as a secondary key.

Examples

Example 1
Input
records = [('Amit', 70), ('Zoya', 90), ('Bina', 90)]
Output
[('Bina', 90), ('Zoya', 90), ('Amit', 70)]
Explanation

Bina and Zoya tie at 90 so they are ordered alphabetically; Amit trails at 70.

Constraints

  • 0 <= len(records) <= 10^4

Topics

ListsSorting

Companies

Goldman SachsJPMorgan Chase

Hints

Hint 1

Use key=lambda r: (-r[1], r[0]) to sort by score desc, name asc in one pass.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.