Meet map()
One function. Every item. A new result.
Same rule, one item at a time.
Want to double every number in a list? map() applies a function to each item. Think of a function as a reusable rule.
1× 222× 243× 264× 28Each item gets its own result. In this example, the original list stays [1, 2, 3, 4].
Give map two things.
A function to use, and items to use it on.
list(map(double, numbers)) doubleThe function- The rule for one item. Here, multiply a number by 2.
numbersThe items- The list to work through, one number at a time.
list(...)Collect the resultsmap()produces results when asked.list()asks for them all and collects them into a list you can see and use.
Use double, without (). You’re handing map the rule; it calls double(1), double(2), and so on for you.
Put it together.
Define the rule, choose your list, then collect the results.
def double(x):
return x * 2
numbers = [1, 2, 3, 4]
result = list(map(double, numbers))
print(result)
[2, 4, 6, 8]Change the rule or numbers to see the code and output update.
New to writing functions?
def double(x): names the rule double. x stands for one number. return x * 2 sends back that number multiplied by 2.
The pattern to remember
list(map(function, items))Apply the function to each item. Collect the results.
What comes out?
1 of 3One rule, applied to every item.
list(map(function, items))Function first. Items second.list() collects the results.
Review the lesson