About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Understanding the map() Function in Python

To implement functions in any program for your software development projects, it is critical to understand the difference between arguments and the return values. The argument represents the input to a function, and the return represents the output of a function.

In Python, there are various built-in functions that allow you to perform various tasks easily without having to define the function. One such function is the map. It allows you to transform all items in an iterable without using loops.

The map function takes the following two arguments and applies the function to each element of the iterable: iterables and a function. The return value is a map object, and this object represents an iterator that can be converted into a list or a set using built-in functions. 

This article will cover the map function, including its syntax and implementation, with various examples for better understanding.

  • The map() function in Python
  • How does the map() function work?
  • map() with built-in functions
  • map() with set
  • map() with tuple
  • map() with lambda
  • Passing multiple iterators to map() using lambda
  • Coding in Pythonic style: Replacing the map() function
  • Advantages and disadvantages of Python's map() function
  • Sample tech interview problems on Python's map() function
  • FAQs on Python's map() function

The map() Function in Python

Definition: map() is a built-in function in Python that allows you to process and transform all the items in an iterable without using a loop. This function accepts functions created by a user (using def or lambda keyword), built-in functions, or methods.

Say you want to use an existing list, apply some operation or function to each element in this list, and create a new list. Usually, you will use the following code to perform this operation:

# Defining a function that returns the square of a number

def squareOfNum(n):

    return n**2

# Existing list

listOfNum = [2, 3, 4, 1, 3]

# New list that contains the squared values

# Creating an empty list

squaredListOfNum = []

# Using loop to iterate over listOfNum and create a new list of SquaredListofNum

for numbers in listOfNum:

    squaredListOfNum.append(squaredListOfNum(numbers))

print(squaredListOfNum) # Output is [4, 9, 16, 1, 9]


Note: The squareOfNum function is a user-defined function.
This approach can be optimized by using the map function.
The syntax is as follows:

This function will return a map object which is an iterator. If you want to create a list from these map objects, then you are required to pass this function to the built-in list function as shown in the following code:

The same task mentioned above can be accomplished using the map function.

# Defining a function that returns the square of a number

def squareOfNum(n):

    return n**2

# Existing list

listOfNum = [2, 3, 4, 1, 3]

# Using map to create a new list squaredList 

squaredListOfNum = list(map(squareOfNum, listOfNum))

print(squaredListOfNum) # [4, 9, 16, 1, 9]

How Does Python’s map() Function Work? 

In general, one parameter of the map function is a function and the other is the iterable. 

When you apply map, it performs f(a), f(b), f(c), etc. Considering the example, the following occurs:

  1. squaredOfNum(2) 🡪 4
  2. squaredOfNum(3) 🡪 9
  3. squaredOfNum(4) 🡪 16
  4. squaredOfNum(1) 🡪 1
  5. squaredOfNum(3) 🡪 9
Note: You can apply the map function to each element in any iterable object or sequence. This is not restricted to only a list.

map() With Built-in Functions

You can pass built-in functions such as len, list, etc., into the map function. 

Example

# Existing list

listOfNames = ["India", "USA"]

print(list(map(len, listOfNames))) # Output is [5, 3]

map() With Set

A set is an unordered sequence of items that you add within curly brackets {}. There cannot be duplicate items in a set. 

Example:

# Creating a function

def changeCharacterToUpper(alpha):

    return str(alpha).upper()

# Creating a set of characters

charList = {"a", "b", "c", "d"}

result = map(changeCharacterToUpper, charList)

print(set(result))  # Output is {'A', 'B', 'C', 'D'}

map() With Tuple

A tuple is a collection of immutable objects. Unlike a list, you cannot change the values inside a tuple once created. Also, it is represented using () brackets.

Example:

# Creating a function

def changeCharacterToUpper(alpha):

    return str(alpha).upper()

# Creating a tuple of characters

characList = ("mary", "Bob", "Alice", "1234john")

result = map(changeCharacterToUpper, characList) # ('MARY', 'BOB', 'ALICE', '1234JOHN')

print(tuple(result))

map() With Lambda

You can optimize your code even further by using the lambda expression as the function argument to the map() function. 

# Defining a function that returns the square of a number

def squareOfNum(n):

    return n**2

# Existing list

listOfNum = [2, 3, 4, 1, 3]

# Using map to create a new list squaredList 

squaredListOfNum = list(map(squareOfNum, listOfNum))

print(squaredListOfNum) # Output is [4, 9, 16, 1, 9]

Passing Multiple Iterators to map() Using Lambda

You can pass multiple iterators into the map function. Also, along with multiple iterators, you are allowed to use different types of iterators at an instance.

Example for multiple iterators:

# Creating two iterators

list1 = [1, 2, 4, 5]

list2 = [5, 2, 8, 3]

# Using map with lambda to pass the two iterators

answer = map(lambda x1, x2: x1+x2, list1, list2)

# Observing the result

print(list(answer))  # Output is [6, 4, 12, 8]

Example for using different types of iterators:

# Creating two types of iterators

list1 = [1, 2, 4, 5]

tuple1 = (5, 2, 8, 3)

# Using map with lambda to pass the two iterators

answer = map(lambda x1, x2: x1*x2, list1, tuple1)

# Observing the result

print(list(answer))  # Output is [5, 4, 32, 15]

Coding in Pythonic Style: Replacing the map() Function

The functionality provided by map can be replaced by using a list comprehension or a generator expression. 

Using a List Comprehension

The entire code provided in the first  section of this article can be replaced using the following line of code:

[squareOfNum(x) for x in listOfNum]

Result:

Using a Generator Expression

Another alternative replacement of map is by using the generator expression. The code to perform the operation to create a new list containing squares of an existing list is as follows:

genExp = (squareOfNum(x) for x in listOfNum)

print(genExp) # Output is  <generator object <genexpr> at 0x0000019ACF73AC80>

print(list(genExp)) # Output is [4, 9, 16, 1, 9]

How to Code With Functional Style in Python

Functional programming represents a paradigm in which you put together all the aspects in a pure mathematical functional style. It focuses more on what to solve rather than how to solve.

It uses expressions instead of statements. Here, an expression represents the evaluation to produce a value, whereas a statement represents an execution to assign some variables.

In Python, you have the following concepts: pure functions, recursion, higher-order functions. 

Pure Functions

Pure functions have two important properties:

  • They produce the same output for the same argument.
  • They do not change or modify the input variable. This is also called immutability.

Example:

# Pure function does not change the input list 

# It returns the new list

def pureFunc(l):    

    newList = []    

    for j in l:

        newList.append(j**3)        

    return newList

originalList = [2, 3, 4, 5]

modifiedList = pureFunc(originalList)

print(modifiedList) # Output is [8, 27, 64, 125]

Recursion

In functional programming, there is no concept of using for loop or while loop. Instead, the recursion concept is used. It represents a process in which a function calls itself directly or indirectly. 

Example:

# Recursion function to find sum of a list

def recursionForSum(l, i, n, count):

    # Base case

    if n <= i:

        return count    

    count =+ l[i]    

    count = recursionForSum(l, i+1, n, count)    

    return count

l = [1, 2, 3]

count = 0

n = len(l)

print(recursionForSum(l, count, n, count)) # Output is 6

Higer-order Functions 

Higher-order functions either:

  • Accept a function as an argument, or
  • Return a function for further processing

Example:

def message1(text): 

    return text.upper()     

def message2(text): 

    return text.lower()     

def message3(func): 

    # storing the function in a variable 

    m = func("I have created a function") 

    print(m)  

message3(message1) 

message3(message2) 

Advantages and Disadvantages of Python’s map() Function

Advantages:

  • Easier to perform operations without using loops
  • Cleaner code
  • Consumes less memory
  • Optimizes the code

Disadvantage: 

Though the map is an elegant function, it does not add a lot of features in terms of performance.

Sample Tech Interview Problems on Python's map() Function

Problem 1: Create a list containing numbers raised to a power provided in another list using map.

Solution:

# Creating a user-defined function 

# You can use the pow() function too

def numAndPowers(n, p):

    return n**p

# Two lists

num = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

powers = [1, 3, 1, 3, 5, 2, 4, 2, 1, 4]

# Using map to create the new list

result = list(map(numAndPowers, num, powers))

print(result)

Result

Problem 2: Create a list of strings by converting a tuple of integers.

Solution:

# Creating a tuple of strings

tupleOfStrings = (123, 14, 2745, 57)

# Converting this tuple into a list of strings

listOfStrings = list(map(str, tupleOfStrings))

print(listOfStrings)

Result:

FAQs on the map() Function in Python

Question 1: What does a map() function return?
Answer: The map() function is an in-built Python function that returns an iterable map object. This iterable object is obtained after applying a function to each item in an iterable. Here's an example:

# map function returns an iterable

powers_of_two = [1, 2 , 4 , 8]

result = map( lambda x : x * x , powers_of_two)

print(list(result))

Output : 

[1, 4, 16, 64]

Question 2: Does the map() function return a new iterable object?

Answer: In Python, lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which represent an iterator from. When you use a map() function, it returns a new iterable object with transformed elements with the same number of data.

Question 3: How do I correctly return the result in map?

Answer: The map() function returns an iterable map object. The output or result specifies the address of this iterable map object. To print the result correctly, you can use list(), set(), or tuple().  Let’s look at an example that returns result of map using set:

# map function returns an iterable

array = [2, 2 , 4 , 6]

result = map( lambda x : x * x , array)

print(set(result))

Output:

{16, 4, 36}

Ready for Your Next Coding Interview?

A technical interview can be overwhelming. While preparing for a coding interview, you must ensure you have covered all ground, including technical concepts and professional and behavioral aspects. Interview Kickstart provides a platform for all the FAANG-aspiring candidates to work on their skills and crack these interviews. 

As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up for our FREE webinar to learn more!

---------

Article contributed by Problem Setters Official