The Wayback Machine - https://web.archive.org/web/20240702200712/https://www.geeksforgeeks.org/python-map-function/
Open In App

Python map() function

Last Updated : 28 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Python map() Function Syntax

Syntax : map(fun, iter)

Parameters:

  • fun: It is a function to which map passes each element of given iterable.
  • iter: It is iterable which is to be mapped.

NOTE: You can pass one or more iterable to the map() function.

Returns: Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)

NOTE : The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) .

There are many more functions like map() functions that are basic concepts of python . These are building blocks for data manipulation and to learn advanced techniques in data science and machine learning, checkout our course Complete Machine Learning & Data Science Program . This course covers everything from basic Python functions to complex machine learning algorithms, equipping you with the skills needed to excel in the field.

map() in Python Examples

Demonstration of map() in Python

In this example, we are demonstrating the map() function in Python .

Python
# Python program to demonstrate working
# of map.

# Return double of n
def addition(n):
    return n + n

# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))

Output
[2, 4, 6, 8]



map() with Lambda Expressions

We can also use lambda expressions with map to achieve above result. In this example, we are using map() with lambda expression.

Python
# Double all numbers using map and lambda

numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))

Output
[2, 4, 6, 8]



Add Two Lists Using map and lambda

In this example, we are using map and lambda to add two lists.

Python
# Add two lists using map and lambda

numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]

result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result))

Output
[5, 7, 9]



Modify the String using map()

In this example, we are using map() function to modify the string. We can create a map from an iterable in Python.

Python
# List of strings
l = ['sat', 'bat', 'cat', 'mat']

# map() can listify the list of strings individually
test = list(map(list, l))
print(test)

Output
[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]



Time complexity : O(n), where n is the number of elements in the input list l.
Auxiliary space : O(n)

if Statement with map()

In the example, the double_even() function doubles even numbers and leaves odd numbers unchanged. The map() function is used to apply this function to each element of the numbers list, and an if statement is used within the function to perform the necessary conditional logic.

Python
# Define a function that doubles even numbers and leaves odd numbers as is
def double_even(num):
    if num % 2 == 0:
        return num * 2
    else:
        return num

# Create a list of numbers to apply the function to
numbers = [1, 2, 3, 4, 5]

# Use map to apply the function to each element in the list
result = list(map(double_even, numbers))

# Print the result
print(result)  # [1, 4, 3, 8, 5]

Output
[1, 4, 3, 8, 5]



Time complexity : O(n)
Auxiliary complexity: O(n)


Conclusion

map() function in Python programming proves to be a powerful tool for transforming data efficiently and concisely. By applying a function to each item in an iterable, map() simplifies code readability and enhances productivity. Whether you’re manipulating lists, tuples, or other iterables, mastering map() empowers you to write cleaner and more expressive Python code. Along with this if you enhance your Python skills with our free Python course , covering everything from basics to advanced topics

Python map() function – FAQs

How to use Python map function with lambda?

You can use map() with a lambda function to apply the lambda function to each element of an iterable. Here’s an example:

numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)

In this example, map() applies the lambda function lambda x: x**2 to each element in the numbers list, producing an iterator (map object) containing the squared values.

How to convert Python map() function to list?

You can convert the map() object to a list using list(). For example:

squared_list = list(squared)

This converts the map object squared (which contains the squared values of numbers) into a list squared_list.

What is a simple Python map() function example?

A simple example using map() without lambda:

def double(x):
return 2 * x
numbers = [1, 2, 3, 4, 5]
doubled = map(double, numbers)

Here, map() applies the double function to each element in numbers, producing an iterator (map object) containing the doubled values.

How to use Python map() function with multiple arguments?

You can use map() with multiple iterables and a function that accepts multiple arguments. For example:

numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
added = map(lambda x, y: x + y, numbers1, numbers2)

Here, map() applies the lambda function lambda x, y: x + y to pairs of elements from numbers1 and numbers2, producing an iterator (map object) containing the sums.

What happens when Python map() function is applied over a list?

When map() is applied over a list, it returns a map object, which is an iterator that yields results lazily as they are needed. To get the results as a list, you typically convert the map object using list() .



Previous Article
Next Article

Similar Reads

Maximum length of consecutive 1's in a binary string in Python using Map function
We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this problem within single line of code in Python. The a
1 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python map function to find row with maximum number of 1's
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve this problem in python quickly using map() function
1 min read
Python map function | Count total set bits in all numbers from 1 to n
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t
2 min read
Python - pass multiple arguments to map function
The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc.) and returns a list of results or map object. Syntax : map( function, iterable ) Parameters : function: The function which is going to execute for each iterableiterable: A sequence or collection of iterable objects whi
3 min read
Sum 2D array in Python using map() function
Given a 2-D matrix, we need to find sum of all elements present in matrix ? Examples: Input : arr = [[1, 2, 3], [4, 5, 6], [2, 1, 2]] Output : Sum = 26 This problem can be solved easily using two for loops by iterating whole matrix but we can solve this problem quickly in python using map() function. C/C++ Code # Function to calculate sum of all el
2 min read
Map function and Dictionary in Python to sum ASCII values
We are given a sentence in the English language(which can also contain digits), and we need to compute and print the sum of ASCII values of the characters of each word in that sentence. Examples: Input : GeeksforGeeks, a computer science portal for geeksOutput : Sentence representation as sum of ASCII each character in a word: 1361 97 879 730 658 3
2 min read
How to Map a Function Over NumPy Array?
In this article, we are going to see how to map a function over a NumPy array in Python. numpy.vectorize() method The numpy.vectorize() function maps functions on data structures that contain a sequence of objects like NumPy arrays. The nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays.
2 min read
Python | Reverse Geocoding to get location on a map using geographic coordinates
Reverse geocoding is the process of finding a place or a location address from a given pair of geographic coordinates(latitude and longitude).Modules needed: reverse_geocoder: A Python library for offline reverse geocoding. pprint: A module which helps to "pretty-print" any arbitrary python data structure. Installation: The modules can be easily in
1 min read
Python PIL | ImagePath.Path.map() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImagePath module is used to store and manipulate 2-dimensional vector data. Path objects can be passed to the methods on the ImageDraw module. ImagePath.Path.map() maps the path through the function. Syntax: ImagePath.Path.map(function) Para
1 min read
Practice Tags :
three90RightbarBannerImg