The map()
function in Python is a built-in function used to apply a given function to each item in an iterable (like a list, tuple, etc.) and return a new iterable (a map
object) with the results.
Syntax
- function: A function to apply to each element of the iterable.
- iterable: One or more iterables to be processed.
- If multiple iterables are passed, the function must accept as many arguments as there are iterables, and it is applied element-wise.
Returns
A map
object, which is an iterator. You can convert it to a list, tuple, or another collection type as needed.
Examples
Single Iterable
Multiple Iterables
Using a Predefined Function
Lazy Evaluation
The map()
function doesn’t execute until explicitly iterated over:
Key Points
- Performance:
map()
is often faster than list comprehensions for applying simple functions, as it doesn’t require the overhead of constructing a list in memory. - Readable Alternative: In some cases, list comprehensions are preferred for readability:
- Compatibility: If you need compatibility across Python 2 and 3, be aware that
map()
in Python 3 returns a lazy iterator, whereas in Python 2, it directly returns a list.