Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python map() function
Next article icon

Python map() function

Last Updated : 23 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Table of Content

  • Converting map object to a list
  • map() with lambda
  • Using map() with multiple iterables
  • Examples of map() function
    • Converting to uppercase
    • Extracting first character from strings
    • Removing whitespaces from strings
    • Calculate fahrenheit from celsius

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.


Next Article
Python map() function

P

pawan_asipu
Improve
Article Tags :
  • Misc
  • Python
  • python-list
  • python-map
  • python-list-functions
Practice Tags :
  • Misc
  • python
  • python-list

Similar Reads

    divmod() in Python and its application
    In Python, divmod() method takes two numbers and returns a pair of numbers consisting of their quotient and remainder. In this article, we will see about divmod() function in Python and its application. Python divmod() Function Syntaxdivmod(x, y)x and y : x is numerator and y is denominatorx and y m
    4 min read
    Enumerate() in Python
    enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
    3 min read
    eval in Python
    Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program.Python eval() Function SyntaxSyntax: eval(expression, globals=None, locals=None)Parameters:expression: String is parsed and evaluated as a Python expressio
    5 min read
    filter() in python
    The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python:Example Usage of filter()Python# Function to check if a number is even def even(n): return n % 2 == 0 a = [1
    3 min read
    float() in Python
    Python float() function is used to return a floating-point number from a number or a string representation of a numeric value. Example: Here is a simple example of the Python float() function which takes an integer as the parameter and returns its float value. Python3 # convert integer value to floa
    3 min read
    Python String format() Method
    format() method in Python is a tool used to create formatted strings. By embedding variables or values into placeholders within a template string, we can construct dynamic, well-organized output. It replaces the outdated % formatting method, making string interpolation more readable and efficient. E
    8 min read
    Python - globals() function
    In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope. This function is particularly useful when you want to in
    2 min read
    Python hash() method
    Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer that is used to quickly compare dictionary keys while looking at a dictionary.Python hash() function SyntaxSyntax : hash(obj)Parameters : obj : The object which we need t
    6 min read
    hex() function in Python
    hex() function in Python is used to convert an integer to its hexadecimal equivalent. It takes an integer as input and returns a string representing the number in hexadecimal format, starting with "0x" to indicate that it's in base-16. Example:Pythona = 255 res = hex(a) print(res)Output0xff Explanat
    2 min read
    id() function in Python
    In Python, id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location. Python id() Fun
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences