Python Map Function
What does map() do?
The map()
function applies a given function to each item of one or more iterables (like lists or tuples) and returns an iterator of the results. It's a concise way to transform data without writing explicit loops.
Basic Syntax
map(function, iterable, ...)
function
: A function to apply to each item. This can be a built-in function, a user-defined function, or a lambda.iterable
: One or more iterables (e.g., lists, tuples).
map()
returns an iterator. To see the results, convert it to a list or tuple, or iterate over it.
Returning an Iterator
numbers = [1, 2, 3]
squared = map(lambda x: x ** 2, numbers)
print(squared) # Output: <map object at ...>
print(list(squared)) # Output: [1, 4, 9]
Converting map object to list/tuple
You often convert the result to a list or tuple:
result = map(str, [1, 2, 3])
print(list(result)) # Output: ['1', '2', '3']
Examples with lambda functions
words = ["apple", "banana", "cherry"]
lengths = map(lambda w: len(w), words)
print(list(lengths)) # Output: [5, 6, 6]
Mapping over multiple iterables
If you provide multiple iterables, the function must take as many arguments as there are iterables. The mapping stops at the shortest iterable.
a = [1, 2, 3]
b = [4, 5, 6]
sums = map(lambda x, y: x + y, a, b)
print(list(sums)) # Output: [5, 7, 9]
Summary
map()
applies a function to each item in one or more iterables.- Returns an iterator; convert to list/tuple to see results.
- Useful for transforming data without explicit loops.
- Works with built-in, user-defined, or lambda functions.
- Stops at the shortest iterable if multiple are provided.