Pattern 4, Filtering. Keep the items that pass a test, discard the rest. The result is a smaller list of the same kind of thing.
Pattern 5, Mapping. Transform every item into something else. The result is the same size but a different kind of thing. Filtering shortens, mapping converts.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Filter the list down to the numbers greater than 3, then map those to their squares and print the result.
loading editor…
Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.
✦ The shortcuts, once you understand the loops
Both languages have built-in one-liners: Python's [n * 2 for n in nums] and JavaScript's nums.map(n => n * 2). Learn the loop first. The shortcut is only readable once you know exactly what it is doing underneath.
Pattern 6, Finding extremes. The minimum or maximum, which you met in Module 21. Start from the first real item, replace when beaten.
EXAMPLE
loading editor…
YOUR TURN
Your turn → One character separates minimum from maximum. Change < to > and rename lowest to highest, then add a second loop that adds up all the hours and prints the total.
loading editor…
Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.
Mark this lesson complete
Signed in, your progress follows you to every device.