The map()
function in Python is a built-in function that takes a function and an iterable (like a list) as arguments. It applies the function to each element of the iterable, returning a new iterable with the results. It is commonly used to efficiently perform operations on all elements of a list without using a loop.
Return Values
The map()
function in Python returns an iterator that applies a function to every item.
How to Use map()
in Python
The map()
function in Python applies a specific function to all items in an iterable and returns a new iterable with the results.
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x*2, numbers))
# Output: [2, 4, 6, 8]
You can also use map()
with multiple iterables. The function will be applied to items from all iterables in parallel.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
description = list(map(lambda x, y: f'{x} is {y} years old', names, ages)
# Output: ['Alice is 25 years old', 'Bob is 30 years old', 'Charlie is 35 years old']
If you have more than one iterable, but the function takes a single argument, you can unpack the iterables using the *
operator.
names = ['Alice', 'Bob', 'Charlie']
uppercase_names = list(map(lambda x: x.upper(), *names))
# Output: ['A', 'B', 'C']