Back to questions
JuniorTheoryCommon
What does the program print?
people = [("ann", 31), ("bob", 25), ("cid", 31)]
by_age = sorted(people, key=lambda p: p[1])
print([name for name, age in by_age])['bob', 'ann', 'cid']
- Expecting
cidbeforeann:sortedis stable, so items with equal keys keep their original order, andanncame beforecidinpeople. - Expecting the names in their original order:
key=lambda p: p[1]makessortedcompare only the ages, sobob, aged25, comes first.
- How would you sort the same list from the oldest to the youngest?
- What would
sorted(people)withoutkeycompare first?