Python Map() Function

Python Map() Function

6 mins read666 Views Comment
Updated on Oct 3, 2023 12:24 IST

This article will tell you about the map function in Python. About its use with a dictionary, tuple, string, lambda function, built-in function.

python map function

 

Python is an object-oriented programming language that also offers several functional programming utilities. In this article, we will focus on one of the most special in-built functions it offers – the map() method. This method allows us to process and transform iterable (such as a list, tuple, set, dictionary, etc.) without using loops in the program. This effectively reduces the size of our code and thus makes it execute faster. In this article, you will learn about Python Map() Function.

We will be covering the following sections today:

Python Map() Function Syntax

Here’s the syntax for this predefined method in Python:

map(function, iterator1, iterator2...iteratorN)

Let’s talk about the arguments passed to this method as illustrated in the syntax above:

  • Function: This is a mandatory argument that specifies a transformation function that will be applied to all items of the iterator(s). 
  • Iterator: This is a mandatory argument that provides an iterable object. We can pass multiple iterable objects to the map() method.

The method returns an iterable map object that can be used further in your Python code.

How to Convert Celsius to Fahrenheit in Python
Understanding Literals in Python
Type Casting in Python

 Also Read: Python Projects for Beginners

Also Read: Powerful Python Libraries for Data Science and Machine Learning

Also Read: Top Python for Data Science Courses to Take Up in 2021

How does the Map() Method Work?                         

The function argument given to the map() method is a transformation function that will iterate over all the items present in the given iterator

For example, let’s see how we will use this method to find the cube of each number in a given list:


 
#Define a function
def cube(n):
return n*n*n
#Declare a list
my_list = [0,2,4,6,8,10,12]
#Apply the map() method
new_list = map(cube, my_list)
print(new_list)
print(list(new_list))
Copy code
Output:
2022_10_image-51.jpg

What have we done here?

As you can see from the code above, we defined a function that returns the cube of a given number. Then, we created a list of numbers, which is the iterator. 

The cube() function and the list were given as arguments to the map() method. The method applies the cube() function to all the list items and returns a map object <map object at 0x0000002C59601748>.

We then apply the list() method to the map object to get the final output – a list with cube values.

We have already seen how the map() method is used with a list of numbers. Now, let’s see how it works with other iterable objects –

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

 Using Map() Method with a Tuple as an Iterator

Let’s consider the following example. Here, we have defined a function that multiplies the items of a tuple by 10:


 
#Define a function
def Func(tup):
return tup*10
#Declare a tuple
tup1 = (2, 3.4, 5, 7.91, 9)
#Apply the map() method
my_tuple = map(Func, tup1)
tuple(my_tuple)
Copy code

 
<strong>Output</strong>
(20,34.0,50,79.1,90)
Copy code

Using Map() Method with a String as an Iterator

A Python string acts like an array, so one can easily use the map() method.

Let’s consider the following example. Here, we have defined a function that converts a given string from lowercase to uppercase:


 
#Define a function
def Func(s):
return s.upper()
#Declare a string
string1 = "nAukri learNing wElcomes yoU"
#Apply the map() method
my_list = map(Func, string1)
print(my_list)
for i in my_list:
print(i, end="")
Copy code

Output:

2022_10_image-52.jpg

Using Map() Method with a Dictionary as an Iterator

Let’s consider the following example. Here, we have defined a nested function that re-assigns the group for all students working on a given project:

#Declare a dictionary
project = [
  {"name": "Will", "Group": 3},
  {"name": "Max", "Group": 2},
  {"name": "Steve", "Group": 4},
  {"name": "Nancy", "Group": 1},
  {"name": "Mike", "Group": 3},
  {"name": "Dustin", "Group": 4},
  {"name": "Robin", "Group": 1},
]
 
#Define a function
def Func(project, new_group):
  def apply(x):
    x["Group"] = new_group
    return x
  return map(apply, project)
 
assigned_group = Func(project, 2)
print(list(assigned_group))

Output:

2022_10_image-53.jpg

Using Map() Method with a Set as an Iterator

Let’s consider the following example. Here, we have defined a function that finds the factorial of the values in the given set:

#Define a function
def Func(n):
   if (n==1):
       return n
   else:
       return n * Func(n-1)
 
#Declare a set
set1 = {2,3,4,5,6}
 
#Apply the map() method
my_set = map(Func, set1)
 
set(my_set)

Output:

2022_10_image-54.jpg

Using Map() Method with Built-in Functions in Python  

We can use any callable function with the map() method, such as class methods, instance methods, static methods, or a particular method called __call__(), etc. Apart from these, we can also use many built-in functions, provided that any function being used takes at least one parameter and returns a value.

Let’s consider the following example of using the built-in sqrt() function from the math module of Python. This function finds the square root of a number.


 
#Import math module
import math
#Declare a tuple
tup1 = (9, 4, 144, 121, 6)
#Apply the map() method with in-built sqrt() function
my_tuple = map(math.sqrt, tup1)
tuple(my_tuple)
Copy code
Output:
2022_07_image-79.jpg

Let’s consider another example of using the built-in len() function to determine the length of an iterable with string items:


 
#Declare a tuple
list1 = ["Naukri", "Learning", "welcomes", "you"]
#Apply the map() method with in-built len() function
my_list = map(len, list1)
list(my_list)
Copy code

Output:

2022_10_image-55.jpg

Using Map() Method with Lambda Function in Python   

Another function we commonly use while working with the map() method is the lambda function. Lambda is a short function without a name which comes in handy when you need to pass an expression-based function to map(). 

For example, let’s try to reimplement the above example of cube values using a lambda function:

#Declare a list
my_list = [0,2,4,6,8,10,12]
 
#Apply the map() method with lambda function
cube = map(lambda n: n*n*n, my_list)
 
list(cube)
Output:
[0,8,64,216,512,1000,1728]

Passing Multiple Iterators to the Map() Method       

If we pass multiple iterators to the map() method, then the transformation function must take as many parameters as the iterators you have supplied. For each iteration, the map() will pass an item from each iterator as a parameter to the function. The number of iterations is the same as the length of the shortest iterator.

Let’s consider the following example using the built-in pow() function with two tuple objects:

#Declare tuple 1
tup1 = (0,2,4,1,6)
 
#Declare tuple 2
tup2 = (1,3,5,7)
 
#Apply the map() method with in-built pow() function
my_tuple = map(pow, tup1, tup2)
 
tuple(my_tuple)

Output: 

(0,8.1024,1)

What have we done here?

The pow() function takes two arguments and returns the value to the power of. 

  • In the first iteration, and. Hence, the result would be. 
  • In the second iteration, and. Hence, the result would be. 
  • In the third iteration, and. Hence, the result would be. 
  • In the fourth iteration, and. Hence, the result would be. 

There is no fifth iteration because the length of the shorter iterator, i.e., tup1, is 4. So, the map() method allows you to process multiple iterators using different operations.

Now, let’s look at a few more examples where we use the lambda function with multiple iterators:

Example 1:

#Example
list(map(lambda x, y, z: x * y * z, [0, 2, 4, 6], [7, 5, 3, 1], [7, 5, 3, 1]))
 

Output:

2022_10_image-56.jpg

What have we done here?

The lambda function takes three arguments and returns the product of three lists (iterators) with 4 items each.

Example 2:

#Example
set(map(lambda x, y: x + y, {1, 2, 3}, {4, 5, 6}))
 
Output:
{5,7,9}

What have we done here?

The lambda function takes two arguments and returns the sum of the two sets (iterators) with 3 items each.

Endnotes

I hope this article was helpful for you to understand the working of the map() function based on the arguments passed to this method through various examples in Python. We also learned how to apply map () to different iterable objects in Python. You can explore related articles here to learn more about Python and practice Python programming.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio