Home › Learn › Python › Functions in depth

lambda, map, and filter

Lesson 33 of 40. Small anonymous functions and the tools that take them.

lambda x: x * 2 is a one-expression function without a name. It is for the places that want a function as an argument and the function is too small to deserve a def: key= in sorting, map, filter. map(f, items) applies f to every item; filter(f, items) keeps the items where f returns true. Both return lazy iterators, so wrap them in list() to see the values.

Comprehensions do the same jobs and are often clearer; both are worth recognizing because you will read code written either way.

nums = [1, 2, 3, 4]
print(list(map(lambda n: n * n, nums)))            # [1, 4, 9, 16]
print(list(filter(lambda n: n % 2 == 0, nums)))    # [2, 4]
print(sorted(["bb", "a", "ccc"], key=lambda s: -len(s)))

Your task

Write doubled(nums) returning every number doubled, long_words(words, n) returning the words longer than n characters, and sort_by_last(names) returning full names sorted by their last word.

Hint 1

list(map(lambda n: n * 2, nums))

Hint 2

sorted(names, key=lambda full: full.split()[-1])

Show the solution
def doubled(nums):
    return list(map(lambda n: n * 2, nums))


def long_words(words, n):
    return list(filter(lambda w: len(w) > n, words))


def sort_by_last(names):
    return sorted(names, key=lambda full: full.split()[-1])

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.