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

Python map() function

Last Updated : 23 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator).

Let’s start with a simple example of using map() to convert a list of strings into a list of integers.

Python
s = ['1', '2', '3', '4']
res = map(int, s)
print(list(res))

Output
[1, 2, 3, 4]

Explanation: Here, we used the built-in int function to convert each string in the list s into an integer. The map() function takes care of applying int() to every element

Syntax of the map() function

The syntax for the map() function is as follows:

map(function, iterable)

Parameter:

  • function: The function we want to apply to every element of the iterable.
  • iterable: The iterable whose elements we want to process.

Note: We can also pass multiple iterables if our function accepts multiple arguments.

Converting map object to a list

By default, the map() function returns a map object, which is an iterator. In many cases, we will need to convert this iterator to a list to work with the results directly.

Example: Let’s see how to double each elements of the given list.

Python
a = [1, 2, 3, 4]

# Using custom function in "function" parameter
# This function is simply doubles the provided number
def double(val):
  return val*2

res = list(map(double, a))
print(res)

Output
[2, 4, 6, 8]

Explanation:

  • The map() function returned an iterator, which we then converted into a list using list(). This is a common practice when working with map()
  • We used a custom function to double each value in the list a. The result was mapped and converted into a list for easy display.

map() with lambda

We can use a lambda function instead of a custom function with map() to make the code shorter and easier. Let’s see how to improve the above code for better readability.

Python
a = [1, 2, 3, 4]

# Using lambda function in "function" parameter
# to double each number in the list
res = list(map(lambda x: x * 2, a))
print(res)

Output
[2, 4, 6, 8]

Explanation: We used lambda x: x * 2 to double each value in the list a. The result was mapped and converted into a list for easy display.

Using map() with multiple iterables

We can use map() with multiple iterables if the function we are applying takes more than one argument.

Example: In this example, map() takes two iterables (a and b) and applies the lambda function to add corresponding elements from both lists.

Python
a = [1, 2, 3]
b = [4, 5, 6]
res = map(lambda x, y: x + y, a, b)
print(list(res))

Output
[5, 7, 9]

Examples of map() function

Converting to uppercase

This example shows how we can use map() to convert a list of strings to uppercase.

Python
fruits = ['apple', 'banana', 'cherry']
res = map(str.upper, fruits)
print(list(res))

Output
['APPLE', 'BANANA', 'CHERRY']

Explanation: The str.upper method is applied to each element in the list fruits using map(). The result is a list of uppercase versions of each fruit name.

Extracting first character from strings

In this example, we use map() to extract the first character from each string in a list.

Python
words = ['apple', 'banana', 'cherry']
res = map(lambda s: s[0], words)
print(list(res))

Output
['a', 'b', 'c']

Explanation: The lambda function s: s[0] extracts the first character from each string in the list words. map() applies this lambda function to every element, resulting in a list of the first characters of each word.

Removing whitespaces from strings

In this example, We can use map() to remove leading and trailing whitespaces from each string in a list.

Python
s = ['  hello  ', '  world ', ' python  ']
res = map(str.strip, s)
print(list(res))

Output
['hello', 'world', 'python']

Explanation: The str.strip method removes leading and trailing whitespaces from each string in the list strings. The map() function applies str.strip to each element and returning a list of trimmed strings.

Calculate fahrenheit from celsius

In this example, we use map() to convert a list of temperatures from Celsius to Fahrenheit.

Python
celsius = [0, 20, 37, 100]
fahrenheit = map(lambda c: (c * 9/5) + 32, celsius)
print(list(fahrenheit))

Output
[32.0, 68.0, 98.6, 212.0]

Explanation: The lambda function c: (c * 9/5) + 32 converts each Celsius temperature to Fahrenheit using the standard formula. The map() function applies this transformation to all items in the list celsius.



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
Python: Map VS For Loop
Map in Python : Map is used to compute a function for different values 'in a single line of code ' . It takes two arguments, first is function name, that is defined already and the other is list, tuple or any other iterables . It is a way of applying same function for multiple numbers . It generates a map object at a particular location . It works
3 min read
Python OpenCV - Depth map from Stereo Images
OpenCV is the huge open-source library for the computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems.Note: For more information, refer to Introduction to OpenCV Depth Map : A depth map is a picture where every pixel has depth information(rather than RG
2 min read
Plotting World Map Using Pygal in Python
Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write. We might want to plot the World Map with country wise boundaries and mig
3 min read
Python Plotly - How to set colorbar position for a choropleth map?
In this article, we will learn how to set colorbar position for a choropleth map in Python using Plotly. Color bar are gradients that go from bright to dark or the other way round. They are great for visualizing data that go from low to high, like income, temperature, or age. Choropleth maps are used to plot maps with shaded or patterned areas whic
2 min read
Convert a nested for loop to a map equivalent in Python
In this article, let us see how to convert a nested for loop to a map equivalent in python. A nested for loop's map equivalent does the same job as the for loop but in a single line. A map equivalent is more efficient than that of a nested for loop. A for loop can be stopped intermittently but the map function cannot be stopped in between. Syntax:
3 min read
How to make a choropleth map with a slider using Plotly in Python?
Choropleth Map is a type of thematic map in which a set of pre-defined areas is colored or patterned in proportion to a statistical variable that represents an aggregate summary of a geographic characteristic within each area. Choropleth maps provide an easy way to visualize how a variable varies across a geographic area or show the level of variab
2 min read
Animated choropleth map with discrete colors using Python plotly
Animated Choropleth Maps can be implemented by Python Plotly. This map is can be composed of colored polygons. We can easily represent spatial variations of any quantity with the help of choropleth maps. To make choropleth maps some basic inputs are required Geometrical/regional Information: This type of information can be supplied by the GeoJSON f
3 min read
Python script to open a Google Map location on clipboard
The task is to create a python script that would open the default web browser to the Google map of the address given as the command line argument. Following is the step by step process:  Creating the Address_string from command line input : Command line arguments can be read through sys module. The sys.argv array has the first element as the filena
3 min read
Python | Plotting Google Map using gmplot package
gmplot is a matplotlib-like interface to generate the HTML and javascript to render all the data user would like on top of Google Maps. Command to install gmplot : pip install gmplotCode #1 : To create a Base Map [GFGTABS] Python # import gmplot package import gmplot # GoogleMapPlotter return Map object # Pass the center latitude and # center longi
2 min read
Plotting Data on Google Map using Python's pygmaps package
pygmaps is a matplotlib-like interface to generate the HTML and javascript to render all the data users would like on top of Google Maps. Command to install pygmaps : pip install pygmaps (on windows)sudo pip3 install pygmaps (on linix / unix)Code #1 : To create a Base Map. [GFGTABS] Python # import required package import pygmaps # maps method retu
3 min read
Python | Plotting Google Map using folium package
Folium is built on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js (JavaScript) library. Simply, manipulate your data in Python, then visualize it on a leaflet map via Folium. Folium makes it easy to visualize data that's been manipulated in Python, on an interactive Leaflet map. This library has a n
2 min read
Hash Map in Python
Hash maps are indexed data structures. A hash map makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index. The key is unique and immutable. Think of a hash map as a cabinet having drawers with labels for the things stored in them. For example, stor
6 min read
Creating a Contour Map Using Python PyVista
Contour maps are essential for visualizing three-dimensional data on a two-dimensional plane, often used in fields like geography, meteorology, and various scientific disciplines. PyVista, a powerful Python library built on top of the Visualization Toolkit (VTK), offers an intuitive interface for creating and visualizing such maps. In this article,
5 min read
Map vs List comprehension - Python
The map() function is used to apply a given function to every item of an iterable, such as a list or tuple and returns a map object (which is an iterator). Whereas, List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or
3 min read
Difference between map, applymap and apply methods in Pandas
Pandas library is extensively used for data manipulation and analysis. map(), applymap(), and apply() methods are methods of Pandas library in Python. The type of Output totally depends on the type of function used as an argument with the given method. What is Pandas apply() method The apply() method can be applied both to series and Dataframes whe
3 min read
How to find largest key in Scala Map
In Scala, Map is same as dictionary which holds key:value pairs. In this article, we will learn how to find the largest key in given Map in Scala. The max() method is utilized to find the largest element of the map. Syntax: m1.max Here, m1 is name of a map. Let's try to understand it better with help of few examples. Example #1: // Scala program to
1 min read
PyQtGraph – Setting Color Map to Image View
In this article, we will see how we can set a color map to the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget
4 min read
Pyspark Dataframe - Map Strings to Numeric
In this article, we are going to see how to convert map strings to numeric. Creating dataframe for demonstration: Here we are creating a row of data for college names and then pass the createdataframe() method and then we are displaying the dataframe. C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module and
3 min read
Convert pair to value using map() in Pyspark
In this article, we are going to learn how to use map() to convert (key, value) pair to value and keys only using Pyspark in Python. PySpark is the Python library for Spark programming. It is an API for interacting with the Spark cluster using the Python programming language. PySpark provides a simple and easy-to-use API for distributed data proces
3 min read
PySpark map() Transformation
In this article, we are going to learn about PySpark map() transformation in Python. PySpark is a powerful open-source library that allows developers to use Python for big data processing. We will focus on one of the key transformations provided by PySpark, the map() transformation, which enables users to apply a function to each element in a datas
5 min read
Practice Tags :
three90RightbarBannerImg