Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Understanding the map() Function in Python

Last updated by Utkarsh Sahu on Sep 25, 2024 at 11:00 PM | Reading time: 10 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Understanding the map() Function in Python
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

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


Last updated on: 
November 20, 2024
Author

Utkarsh Sahu

Director, Category Management @ Interview Kickstart || IIM Bangalore || NITW.

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

Understanding the map() Function in Python

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image