Working With Map in Python

Introduction

Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.

Syntax of Map in Python

The syntax of the Python map() function is:

map(function, iterables)

In the above syntax:

  • function: It is the transformation function through which all the items of the iterable will be passed.
  • iterables: It is the iterable (sequence, collection like list or tuple) that you want to map.

Let’s look at an example to understand the syntax of the map in Python better. The code below creates a list of numbers and then uses the Python map() function to multiply each item of the list with itself.

# Defining a function

def mul(i):

    return i * i

# Using the map function

x = map(mul, (3, 5, 7, 11, 13))

print (x)

print(list(x))

Output:

MapInPython_1.

As you can see in the code above, the first print function printed the map object as it is. Thus, you have to convert the map object to a list, set, or another iterable item to make it readable.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

Workings of the Python Map() Function 

The map in Python takes a function and an iterable/iterables. It loops over each item of an iterable and applies the transformation function to it. Then, it returns a map object that stores the value of the transformed item. The input function can be any callable function, including built-in functions, lambda functions, user-defined functions, classes, and methods. Now, calculate the same multiplication as you did in the previous example, but this time with both the for loop and the map functions separately, to understand how the map() function works.

Example: Using For Loop

num = [3, 5, 7, 11, 13]

mul = []

for n in num:

    mul.append(n ** 2)

print (mul)

Output:

MapInPython_2

Example: Using the Python Map() Function

def mul(i):

    return i * i

num = (3, 5, 7, 11, 13)

resu = map(mul, num)

print(resu)

# making the map object readable

mul_output = list(resu)

print(mul_output)

Output:

MapInPython_3

As you can see, the map() function iterates through the iterable, just like the for loop. Once the iteration is complete, it returns the map object. You can then convert the map object to a list and print it. You would have also noticed that this time while using the map in Python, you defined the iterable separately and then passed it to the map() function. Thus, you can either define the iterable within the map() function or separately.

Free Course: Programming with Python

Learn the Basics of Programming with PythonEnroll Now
Free Course: Programming with Python

How Map in Python is Used With Built-In Functions

You can also use the Python map() function with built-in functions that are pre-defined. Let’s see this in action.

Example: Using Map() With Len()

In this code, you must use the Python len() function along with map() to find the length of some words.

example = ["Welcome", "to", "Simplilearn"]

x = list(map(len, example))

print(x)

Output:

MapInPython_4

Example: Using Map in Python With Math.Sqrt()

In the program below, you will first import the math library to use the math.sqrt() function with map in Python.

import math

num = [9, 36, 49, 81, 121]

x = list(map(math.sqrt, num))

print(x)

Output:

MapInPython_5

Similar to the above examples, you can use any built-in functions with the map in Python.

Using Map in Python with Lambda Functions

One of the most common use cases of the map function you might encounter is with the lambda functions. Lambda functions are anonymous functions, i.e., without any name. The lambda function allows you to define the function right inside the map() function. Let’s look at an example to see how the Python map() function is used with the lambda functions.

Example: Using Map() with Lambda Functions

In the code mentioned below, you will use a lambda function to double the numbers in the iterable using the map function.

num = (6, 9, 21, 44)

resu = map(lambda i: i + i, num)

print(list(resu))

Output:

MapInPython_6

How Map in Python is Used as an Iterator

You can use the Python map() function with a String. While using the map() with a String, the latter will act like an array. You can then use the map() function as an iterator to iterate through all the string characters. Let’s look at an example to see it in action.

Example: Using Map in Python as an Iterator

def upper(n):

    return n.upper()

stri = "This is Simplilearn"

upd_list = map(upper, stri)

print(upd_list)

print(list(upd_list))

Output:

MapInPython_7

FREE Data Science With Python Course

Start Learning Data Science with Python for FREEStart Learning
FREE Data Science With Python Course

How Map() is Used With Tuple

In this code, you will take a tuple containing some string values. You will then define a function to convert the strings to uppercase. Lastly, you must use the map in Python to use the tuple and the function, to convert the string values to uppercase.

Example: Map() with Tuple

def example(s):

    return s.upper()

tuple_exm = ('this','is','map','in','python', 'article')

upd_tup = map(example, tuple_exm)

print(upd_tup)

print(tuple(upd_tup))

Output:

MapInPython_8

Using Map in Python with Dictionary

A dictionary in Python is another collection type that stores key: value pairs. You can define a dictionary using curly brackets. In the example below, you will use a dictionary of car names and append the names with a ‘_’ in the end by using the map() function. You can see that a lambda function was used for this example.

Example: Using Dictionary with Map()

car_dict ={'a': 'Mercedes-Benz', 'b': 'BMW', 'c': 'Ferrari', 'd': 'Lamborghini', 'e': 'Jeep'}

# adding an '_' to the end of each value

car_dict = dict(map(lambda x: (x[0], x[1] + '_'), car_dict.items() ))

print('The modified dictionary is : ')

print(car_dict)

Output:

MapInPython_9

How to Use Map() With Set

Similar to other iterables, you can also use a set with the Python map() function. In the example below, you must define a set with some numbers and print each value’s remainder when divided by 3.

Example: Using Set and Map()

def example(i):

    return i%3

set_exm = {33, 102, 62, 96, 44, 28, 227}

upd_itms = map(example, set_exm)

print(upd_itms)

print(set(upd_itms))

Output:

MapInPython_10.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Summing It Up

In this article, you learned about the map in Python. You have seen some examples to see how it operates with different functions and iterables. Some of the key points to remember are that the Python map() function is used to apply a transformation function to an entire iterable. Also, you can pass multiple iterables to a single map() function. If you want to learn more about the iterable, map, or other basic Python programming concepts, you can opt for Simplilearn’s Online Python Certification Course

On the other hand, if you are interested in learning Data Science, you can opt for the Data Science with Python Certification Course. Both courses provide hands-on experience with applied learning to help you excel in the relevant fields.

Have any questions for us? Leave them in the comments section and our experts will get back to you on the same, ASAP!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.