Meet map()

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.

4 items in. 4 results out. Same order.

Each 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 results
map() 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.

Choose a rule

Use 1–6 whole numbers from −99 to 99, separated by commas.

PythonMultiply each number by 2
def double(x):
    return x * 2

numbers = [1, 2, 3, 4]
result = list(map(double, numbers))
print(result)
Output[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.

Next lessonHow map works

Explore when results are produced and how inputs pair up.