Python map() Function, Explained with Examples
In this tutorial, you’ll learn how to use the Python map() function to apply a function on all items of an iterable.
Python supports the functional programming paradigm that allows you to define tasks as a computation of functions programmatically. You can treat Python functions as objects: a function can take another function as a parameter and return another function.
The map()
function takes in a function as an argument and lets you apply it to all items in a sequence.
By the end of this tutorial, you’ll be able to use the Python map()
function — to rewrite verbose loops and list comprehensions. You’ll code several examples to understand the different ways you can use the map()
function.
How to Apply a Function to Elements of a Python List
Let’s start our discussion with an example.👩🏫
Here nums
is a list of numbers.
nums = [2,4,3,7]
Next, consider the function self_pow()
. The function self_pow()
takes in a number as the argument and returns the number raised to the power of the number itself: n**n.
In Python, ** is the exponentiation operator. a**b returns the value of a raised to the power b, a^{b}.
def self_pow(n):
return n**n
TODO: To create a new list
nums_pow
by applying the functionself_pow()
to every element in listnums
.
Using for Loop
To do this, you can use for loops in Python:
 For every number in the
nums
list, call the functionself_pow()
withnum
as the argument.  Append the result of the function call to the new list
nums_pow
.
nums_pow = []
for num in nums:
nums_pow.append(self_pow(num))
print(nums_pow)
In the output, every number nums
is raised to itself. The elements in nums_pow
list are as follows: 2^{2}, 4^{4}, 3^{3},7^{7}.
Output
[4, 256, 27, 823543]
Using List Comprehension
You can make this concise using list comprehension. From the explicit for loop above, we can identify the output expression, and the list to loop through.
We can then modify the generic list comprehension expression:
new_list = [<output expression> for item in iterable]
The list comprehension expression to generate the nums_pow
list is as follows:
nums_pow = [self_pow(num) for num in nums]
print(nums_pow)
The output is the same as that from using for loops, as expected.
Output
[4, 256, 27, 823543]
Instead of loop and list comprehension, you can use the Python map()
function with a concise syntax that helps apply the function to all items in an iterable. Let’s start by learning the syntax of the map function.
Python map() Function Syntax
The general syntax to use the Python map()
function is as follows:
map(function, iterable_1,[iterable_2,...,iterable_n])
The map()
function takes in at least two arguments, a function and an iterable.
In the above syntax:
 function denotes a Python function or in general, any Python callable. This includes userdefined and builtin functions, classes, instance and class methods, and more.
 iterable is any valid Python iterable, such as a list, tuple, and string.
 The map() function applies the function to every item in the iterable
What does the map() function return?
It returns a map object. You can then cast the map object to a list using the syntax: list(map(function,iterable)).
Depending on the use case, you can cast it into a Python tuple.
Now that you’ve learned the syntax of the Python map()
function, let’s start coding examples.
You should have Python 3.x to follow along with this tutorial. Else, you can run the code snippets in Geekflare online Python editor.
How to Use map() Function with UserDefined Functions
#1. Previously, we had applied the self_pow()
function to every number in the nums
list. In the syntax for map()
function, we can pass in the function self_pow
and the list nums
as the arguments.
Note: You should only specify the function’s name and not a function call. Use self_pow
and not self_pow()
.
The map()
function returns a map object.
print(map(self_pow,nums))
<map object at 0x7f7d315c14d0>
We can then cast the map object into a list using the list() function, as shown below.
nums_pow = list(map(self_pow,nums))
print(nums_pow)
Here’s the output where every num
in nums
is mapped to num^{num} in nums_pow
list.
Output
[4, 256, 27, 823543]
#2. Consider the following function inch_to_cm()
that converts inches to centimeters. 1 inch = 2.54 cm.
def inch_to_cm(inch):
return inch*2.54
To convert the inch values in the inches
list to centimeters, you can use the map()
function as shown in the code cell below.
inches = [5.54,3.4,1,25,8.2]
cms = list(map(inch_to_cm,inches))
print(cms)
The cms
list contains the inch values expressed in centimeters.
Output
[14.0716, 8.636, 2.54, 63.5, 20.828]
How to Use map() Function with BuiltIn Functions
In this section, we’ll learn how to use map()
with builtin functions in Python.
#1. The list strings
is a list of programming languages. You’d like to create a new list strings_upper
that contains the programming language strings in uppercase.
strings = ['JavaScript','Rust','Python','Go']
The builtin string method
.upper()
acts on a string and returns a copy formatted in uppercase.
strings_upper = list(map(str.upper,strings))
print(strings_upper)
The list strings_upper
includes strings in the list strings
formatted in uppercase.
Output
['JAVASCRIPT', 'RUST', 'PYTHON', 'GO']
#2. The builtin len()
function in Python takes in a sequence as the argument and returns its length. To find the length of each of the strings in the strings
list, we can use the map()
function and apply the length function on each string, as shown below.
strings_len = list(map(len,strings))
print(strings_len)
Output
[10, 4, 6, 2]
#3. You can use the map()
function with other collections such as tuples.
The following example contains a tuple containing information on the number of bedrooms, area, and city in which a house is located.
In Python, the type()
function returns the datatype of any Python object. To get the datatype of all items in this tuple, you can use the map()
function to call the type
function on each tuple item.
house = (2,758.5,'Bangalore')
house_elt_type = tuple(map(type,house))
print(house_elt_type)
We’ve cast the map object into a tuple. You can also cast into a list or any other collection.
In the output below, we see that the datatypes of 2, 758.5, and Bangalore, have been inferred as ‘int’, ‘float’, and ‘str’, respectively.
Output
(<class 'int'>, <class 'float'>, <class 'str'>)
#4. In Python, you can import builtin modules and use the functions defined in the modules.
To compute the square root of every number in the nums
list, you can use the square root function sqrt
from the math module.
import math
nums = [30,90,34,45,97]
nums_sqrt = list(map(math.sqrt,nums))
print(nums_sqrt)
Output
[5.477225575051661, 9.486832980505138, 5.830951894845301, 6.708203932499369, 9.848857801796104]
The above output is difficult to parse and follow. You may want to round each square root value to say, two decimal places.
How to Round a Floating Point Number in Python
Let’s define a function round_2()
that takes a floating point value and rounds it to two decimal places.
def round_2(num):
return round(num,2)
Now, you can use the map()
function with the round_2
and the nums_sqrt
list.
nums_sqrt_round = list(map(round_2,nums_sqrt))
print(nums_sqrt_round)
Output
[5.48, 9.49, 5.83, 6.71, 9.85]
You can also use nested map()
functions, where the inner map function is used to compute the square root list nums_sqrt
, and the outer map function performs the rounding operation.
nums_sqrt_round = list(map(round_2,list(map(math.sqrt,nums))))
print(nums_sqrt_round)
Output
[5.48, 9.49, 5.83, 6.71, 9.85]
The outputs are identical in both of the above approaches. However, you should ensure that the code is readable and maintainable when nesting functions as shown above.
How to Use map() Function with Lambda Functions
In the previous sections, you learned how to use the Python map()
function with builtin and userdefined functions. You’ll now learn how to use the map() function with lambda functions, which are anonymous in Python.
Sometimes, you’ll have a function whose body contains only one line of code, and you may need to use the function only once and not reference it elsewhere in the program. You can define such functions as lambda function in Python.
Note:
lambda args: expression
is the general syntax to use a Python lambda function.
#1. Consider the following list strings
. Suppose you want to get a list strings_rev
– containing a reversed copy of each of the strings.
strings = ['JavaScript','Rust','Python','Go']
We can reverse a Python string using string slicing.
Note: This is a generalization of string slicing expression
str[start:stop:step]
.– Without the
start
andstop
values, the slice starts at the beginning of the string and extends up to the end of the string.
– Negative values ofstep
gives slices starting from the end of the string.
– Therefore,str[::1]
returns a reversed copy of str.
You can use this lambda function: lambda x:x[::1]
Inside the map function, as shown below.
strings_rev = list(map(lambda x:x[::1],strings))
print(strings_rev)
As with other examples, we cast the map object into a list. In the output, we see that each of the strings in the list strings has been reversed.
Output
['tpircSavaJ', 'tsuR', 'nohtyP', 'oG']
#2. In the previous section, we computed the square root of every number in the numbers list and then rounded each square root value to two decimal places.
We used the function round_2()
to do this. Let’s rewrite the round_2()
function as a lambda function and use it with the map()
function described below.
nums_sqrt_round_l =list(map(lambda num:round(num,2),nums_sqrt))
print(nums_sqrt_round_l)
As seen below, the output is identical to what we obtained from using the round_2()
function.
Output
[5.48, 9.49, 5.83, 6.71, 9.85]
How to Use map() Function with Multiple Iterables
In the examples we have seen, we applied a function on all items of exactly one iterable.
Sometimes, we may have functions that take in two or more arguments. In this case, each argument is stored in a list or any similar collection.
We can also use the Python map() function with multiple lists.
#1. Consider the following function area()
that accepts the length
and breadth
as inputs and returns the area, length*breadth
.
def area(length,breadth):
return length*breadth
The length and breadth of different rectangles are stored in two separate lists, lengths
and breadths
, respectively.
lengths = [4,8,10,18]
breadths = [9,4,6,11]
We can use the map()
function to apply the area function on the above lists by passing in both the lengths
and breadths
lists.
areas = list(map(area,lengths,breadths))
print(areas)
Because the function area accepts two arguments, the length and breadth values are used from the lists lengths
breadths
, respectively.
Output
[36, 32, 60, 198]
#2. The Python math module has the log function that helps us compute the logarithm of a number to any base.
Note: log(x, base) returns the value of log x to the base specified by the value base, log _{base} x. If the base is not specified, the default base value is e (log computes the natural logarithm).
In this example:
 The list
x
corresponds to the values for which you’d like to compute the logarithm.  The
base
list contains all base values to be used in the logarithm computation.
x = [2,6,12,10]
base = [2,3,2,5]
We can use the Python map() function with math.log
, the lists, x
and base
to get the new list log_x
, as follows.
log_x = list(map(math.log,x,base))
print(log_x)
Here’s the output.
Output
[1.0, 1.6309297535714573, 3.5849625007211565, 1.4306765580733933]
Conclusion
Here’s a summary of what you’ve learned in this tutorial:
 The Python map() function takes in at least two arguments: a function and an iterable, with the syntax map(function, iterable(s)).
 The function can be any valid Python callable.
 When the function takes in k arguments, use the
map()
function with the function and each of the k arguments in an iterable.
Next, learn to work with sets in Python.
 Tagged in:
 Python
More great readings on Development

How to Install Anaconda on LinuxAnesu Kafesu on September 29, 2022

12 Top Search Solutions for Ecommerce and Big SitesAmrita Pathak on September 27, 2022

11 InApp Chat Solutions to Build Better User EngagementTamal Das on September 22, 2022

Difference Between Bug, Defect, Error, Failure, and Fault in Software TestingAmrita Pathak on September 22, 2022

How to Install Yarn on Windows?Bipasha Nath on September 21, 2022

21 Frequently Asked OOP Interview Questions and Answers to Know TodayDurga Prasad Acharya on September 27, 2022
The more you learn, the better you become.
Every week we share trending articles and tools in our newsletter. More than 10,000 people enjoy reading, and you will love it too.