Python · Level 2 Data

Sorting & Lambdas

Sort any data the way you need it using key functions and short anonymous lambda functions.

  • sorted() vs list.sort()
  • key= functions
  • lambda expressions
  • reverse=True

sorted() returns a new sorted list. Pass key= a function that picks what to compare — a lambda is a tiny one-line function, perfect for this.

words = ["banana", "kiwi", "apple"]

sorted(words)                     # -> ['apple', 'banana', 'kiwi']
sorted(words, key=len)            # -> ['kiwi', 'apple', 'banana']
sorted(words, key=lambda w: w[-1], reverse=True)
# sorts by last letter, Z to A

Write sort_by_age(people) where people is a list of (name, age) tuples. Return a new list sorted by age, youngest first. Don't change the original list.

solution.py
Test Suites Pending
Stdout