Functions and Objects · Functions · lesson 5 of 10
Lambdas, map, filter and sorted
about 14 minutes · free · runs in your browser
Step 1 of 2
Small anonymous functions
A lambda is a function written inline, with no name:
double = lambda n: n * 2 # works, but just use def
Assigning a lambda to a name is worse than def in every way. Where lambdas earn their
place is as an argument to something else — most often sorted:
people.sort(key=lambda p: p["age"])
sorted(words, key=len)
sorted(scores, reverse=True)
The key function is called once per item, and sorting happens on what it returns. Note
that key=len needs no lambda at all — pass the function itself when one already exists.
map(fn, items) and filter(fn, items) apply a function across a collection, though
a comprehension usually reads better.
Your turn: write by_length(words) returning the words sorted shortest to longest,
and by_last_letter(words) sorting by the final character.
You start from this, and edit it in the browser:
def by_length(words):
pass
def by_last_letter(words):
pass
Step 2 of 2
Sorting structured data
key comes into its own with dictionaries and objects, where there is no obvious natural
order.
Returning a tuple from the key sorts by several fields at once — the first element first, then the second as a tie-breaker:
sorted(people, key=lambda p: (p["city"], p["name"]))
Your turn: write ranked(players) sorting by score from high to low, with ties
broken by name alphabetically.
You start from this, and edit it in the browser:
def ranked(players):
# Sort by score descending, then name ascending.
pass