Understanding the Python Map Function
Ohidur Rahman Bappy
MAR 22, 2025
Understanding the Python map()
Function
The map()
function is a built-in utility in Python that allows you to apply a specified function to each item of an iterable (e.g., strings, lists, tuples, or dictionaries) and returns an iterable map object with the results.
map()
Function Signature
map(function, iterable [, iterable2, iterable3,...iterableN]) --> map object
Example with a Simple Function
Consider the following simple square
function:
def square(x):
return x*x
Now, we can use the map()
function to apply this square
function to a list of numbers:
>>> numbers = [1, 2, 3, 4, 5]
>>> sqr_list = map(square, numbers)
>>> list(sqr_list)
[1, 4, 9, 16, 25]
In this example, the map()
function applies the square
function to each element in the numbers
list, returning a map object that can be converted to a list of results.
Using map()
with Lambda Expressions
The map()
function can also be used with lambda functions, providing a convenient way to use small anonymous functions:
>>> sqr_list = map(lambda x: x*x, [1, 2, 3, 4, 5])
>>> list(sqr_list)
[1, 4, 9, 16, 25]
Utilizing map()
with Built-in Functions
You can apply built-in functions using map()
. Below is an example using the pow()
function to map two list objects:
>>> bases = [10, 20, 30, 40, 50]
>>> indices = [1, 2, 3, 4, 5]
>>> powers = list(map(pow, bases, indices))
>>> powers
[10, 400, 27000, 2560000, 312500000]
In this example, pow()
is used to raise each number in bases
to the power of the corresponding number in indices
, resulting in a list of computed powers.