Start free

Intermediate · Sorting · 146 of 264

Sort by age

Sort people by age, youngest first; people of the same age by name.

Input: n, then n lines "name age". Output: the names in that order, one per line.

Examples

Input
3
ann 30
bob 25
cid 30
Output
bob
ann
cid
Input
1
zoe 9
Output
zoe

One more test checks other inputs when you press Check.

Stuck? The idea behind sorting

sorted() gives a new sorted list; list.sort() sorts the list itself. reverse=True sorts from largest to smallest.

key= says what to sort by: key=len sorts words by length, key=lambda p: p[1] sorts pairs by their second item.

people = [("Ann", 14), ("Bob", 12)]
for name, age in sorted(people, key=lambda p: p[1]):
    print(name, age)

Watch for: list.sort() gives back None: names = names.sort() loses the list. Use sorted() for a new one.

All the sorting exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More sorting exercises