What is the use of map function in Python?
In this article, we will learn the use of map function in Python.
What is the map() function?
Python’s map() function applies a function to each item in the iterator provided as input. Lists, tuples, sets, dictionaries, or strings can all be used as iterators, and they all return iterable map objects. map() is a built-in function of Python.
grammar
map(function, iterator1,iterator2 ...iteratorN)
parameter
function - It is necessary to provide a map with a function that will be applied to all available items of the iterator.
iterator - Forces an iterable object. It can be a list, tuple, etc. The map() function accepts multiple iterator objects as parameters.
return value
The map() method applies the specified function to each item in the iterator and produces a tuple, list, or another iterable map object.
How does the map() function work?
Functions and iterable objects are the two inputs of the map() function. The function passed to map() is a normal function that will iterate over each value in the specified iterable object.
Use map() with a list of numbers
Example
The following program uses the map() function in Python Adds 5 to each element in the list -
# creating a function that accepts the number as an argument def exampleMapFunction(num): # adding 5 to each number in a list and returning it return num+5 # input list inputList = [3, 5, 1, 6, 10] # Passing above defined exampleMapFunction function # and given list to the map() function # Here it adds 5 to every element of the given list modifiedList = map(exampleMapFunction, inputList) # printing the modifies list(map object) print(modifiedList) # converting the map object to the list and printing it print("Adding 5 to each element in a list using map():\n", list(modifiedList))
Output
<map object at 0x7fb106076d10> Adding 5 to each element in a list using map(): [8, 10, 6, 11, 15]
Use map() and dictionary
Python uses dictionaries to implement the more common associative arrays. A dictionary is a set of key-value pairs. It is defined using curly braces {}.
Dictionaries are dynamic and constantly changing. They can be changed and deleted as needed. Dictionary items can be accessed using keys, but list elements are retrieved by index based on their position in the list, this is how dictionaries differ from lists.
Since a dictionary is an iterator, you can use it inside the map() function.
Example
The following program adds 5 to each element in a dictionary using the map() function in Python -
# creating a function that accepts the number as an argument def exampleMapFunction(num): # adding 5 to each number in a dictionary and returning it return num + 5 # input Dictionary inputDictionary = {2, 3, 4, 5, 6, 7, 8, 9} # passing above defined exampleMapFunction function # and input dictionary to the map() function # Here it adds 5 to every element of the given dictionary modifiedDict = map(exampleMapFunction, inputDictionary) # printing the modified dictionary(map object) print(modifiedDict) # converting the map object to the list and printing it print("Adding 5 to each element in a dictionary using map():\n", list(modifiedDict))
Output
<map object at 0x7fb1060838d0> Adding 5 to each element in a dictionary using map(): [7, 8, 9, 10, 11, 12, 13, 14]
Use map() function and tuple
In Python, a tuple is an object whose elements are separated by commas and enclosed in parentheses.
Example
The following code uses the lower() and map() functions to convert all items in the tuple to lowercase:
# creating a function that accepts the number as an argument def exampleMapFunction(i): # converting each item in tuple into lower case return i.lower() # input tuple inputTuple = ('HELLO', 'TUTORIALSPOINT', 'pyTHON', 'CODES') # passing above defined exampleMapFunction function # and input tuple to the map() function # Here it converts every element of the tuple to lower case modifiedTuple = map(exampleMapFunction, inputTuple) # printing the modified tuple(map object) print(modifiedTuple) print('Converting each item in a tuple to lowercase:') # converting the map object to the list and printing it print(list(modifiedTuple))
Output
<map object at 0x7fb10f773590> Converting each item in a tuple to lowercase: ['hello', 'tutorialspoint', 'python', 'codes']
Using map() and other function tools in Python
Using map() together with functional tools such as filter() and reduce(), we can perform more complex changes on iterable objects.
Use map() and filter() functions
In some cases, we have to process the input of an iterable and return another iterable object by removing/filtering unnecessary items from the input. In this case, Python's filter() is a wise choice.
filter()The function returns the iterable input items that satisfy the function return true.
If no function is passed, filter() will use the identity function. This means that filter() checks the true value of each item in the iterable and removes any false values.
Example
The following function uses a combination of filter() and map() functions to filter all positive numbers in the list and return their square roots -
# importing math module import math # creating a function that returns whether the number # passed is a positive number or not def isPositive(n): return n >= 0 # creating a function that filters all the positive numbers # from the list and returns the square root of them. def filterSqrtofPositive(nums): # filtering all the positive numbers from the list using filter() # and returning the square root of them using the math.sqrt and map() filteredItems = map(math.sqrt, filter(isPositive, nums)) # returning the list of filetred elements return list(filteredItems) # input list inputList= [16, -10, 625, 25, -50, -25] # calling the function by passing the input list print(filterSqrtofPositive(inputList))
Output
[4.0, 25.0, 5.0]
in conclusion
Python’s map() function allows you to perform operations on iterable objects. Map() is typically used to convert and manipulate iterable objects without looping.
In this article, we took several data types as examples and learned how to use the map() method in Python.
The above is the detailed content of What is the use of map function in Python?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.
