Read Code Fast
Lesson 5 Loops as words
filter, map, find, any, all, count and sum, in loop form and in one-line form
What you'll learn
- Name a loop at a glance: filter, map, find, any, all, count or sum
- Turn the long loop form into its one-word form and back
- Spot the loops an AI got subtly wrong
Most loops in AI-written code are one of seven words. Once you can name the word, you don't read the loop, you recognise it.
The idea
Seven words cover most loops. filter keeps some items. map changes every item. find returns the first match. any asks if at least one matches. all asks if every one matches. count says how many match. sum adds them up. The long form is a for loop with an if or an accumulator; Python's short form is a comprehension, or a call such as any, all and sum. They mean the same thing.
To name a loop, look at what it builds and what its if asks. A loop that pushes only some items is a filter. One that pushes a changed item for every item is a map.
1names = []2for user in users:3 if user["active"]:4 names.append(user["name"])56# the same thing in one line:7same_names = [u["name"] for u in users if u["active"]]
- Line 3 The
ifasks a question and skips some users: that's a filter. - Line 4 It appends the name, not the user: that's a map.
- Line 7 A comprehension reads in order: take the name, from each user, if active.
Take away
- Seven words: filter, map, find, any, all, count, sum.
- Ask what the loop builds and what its
ifasks. - Read the word, then check only what can differ: the condition, and what comes back when nothing matches.
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.