CodeMIRAI
0 XP

map, filter and sorted

2 min read 6 runnable examples Quiz included

In Python, functions are values like any other: you can store them in variables, put them in lists and pass them to other functions. Functions that take other functions are called higher-order functions.

Python
def shout(text):
    return text.upper() + "!"

speak = shout              # no brackets: the function itself, not a call
print(speak("hello"))

for f in [str.upper, str.lower, str.title]:
    print(f("hello WORLD"))

map(): apply a function to every item

Python
prices = ["19.99", "5", "120.50"]
numbers = list(map(float, prices))
print(numbers)

names = ["asha", "leo", "mei"]
print(list(map(str.title, names)))
print(list(map(lambda n: n * 2, [1, 2, 3])))

map returns a lazy object; wrap it in list() to see the results.

filter(): keep the items that pass a test

Python
numbers = [4, 11, 8, 3, 15, 6]
print(list(filter(lambda n: n > 5, numbers)))

words = ["apple", "", "kiwi", "", "fig"]
print(list(filter(None, words)))     # None keeps truthy items

Comprehensions usually read better

The same jobs as list comprehensions:

Python
numbers = [4, 11, 8, 3, 15, 6]
print([n * 2 for n in numbers])          # like map
print([n for n in numbers if n > 5])     # like filter

Most Python developers prefer comprehensions for anything involving a lambda; map is still neat with an existing function, such as map(int, input().split()).

sorted() with a key

You met this in the lambda lesson. sorted() takes any iterable and a key function:

Python
files = ["report.pdf", "a.txt", "photo.jpeg", "notes.md"]
print(sorted(files, key=len))
print(sorted(files, key=lambda f: f.split(".")[-1]))   # by extension

any() and all()

any() is true if at least one item is truthy; all() if every item is:

Python
scores = [72, 95, 88, 61]
print(any(s > 90 for s in scores))     # did anyone score over 90?
print(all(s >= 60 for s in scores))    # did everyone pass?

password = "Secret123"
checks = [len(password) >= 8, any(c.isdigit() for c in password), any(c.isupper() for c in password)]
print("Strong password:", all(checks))
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.