What is the purpose of map function in Python
What is the purpose of the map function in Python?
In this article, we’ll learn about the purpose of the map function in Python.
What is the map() function?
Python The map() function applies a function to each item in an iterable. Any list, tuple, set, dictionary, or string can be used as an iterator, and they all return an iterable map object. Map() is a built-in Python function.
Syntax
map(function, iterator1,iterator2 ...iteratorN)
Parameters
- function – It is necessary to provide a function to map, which will be applied to all available items in the iterator.
-
iterator – A mandatory iterable object. It can be a list, tuple, etc. The map() function accepts multiple iterator objects as arguments.
Return Value
The map() method applies a specified function to each item in an iterable, producing a tuple, list, or other iterable map object.
How the map() Function Works
The function and the iterable are the two inputs to the map() function. The function passed to map() is a normal function that loops over each value in the specified iterable.
List of Numbers Using map()
Example
The following program uses the Python map() function to add 5 to each element in a 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 the above defined exampleMapFunction function
# and the given list to the map() function
# Here it adds 5 to every element of the given list
modifiedList = map(exampleMapFunction, inputList)
# printing the modified 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]
Using map() in a Dictionary
Python uses dictionaries to implement what are often called associative arrays. A dictionary is a collection of key-value pairs. It is defined using curly braces ().
Dictionaries are dynamic and mutable. They can be modified and deleted as needed. Dictionary items can be accessed using a key, but list elements are retrieved by their index within the list, which is what makes dictionaries different from lists.
Since a dictionary is an iterator, you can take advantage of it in the map() function.
Example
The following program uses the map() function in Python to add 5 to each element in the dictionary —
# 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]
Using map() with tuples
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 a 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 Functional Tools in Python
Using map() with functional tools like filter() and reduce() allows us to perform more complex transformations on iterables.
Using map() and filter()
In some cases, we must process an iterable input and return another iterable by removing/filtering unnecessary items from the input. In such cases, Python’s filter() is a wise choice.
filter() returns the iterable of input items for which the function returns true.
If no function is passed, the identity function is used by filter(). This means that filter() checks the truth value of each item in the iterable and removes all false values.
Example
The following function filters all positive numbers from a list and returns their square roots using the filter() and map() functions.
# 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]
Conclusion
Python’s map() function allows you to operate on iterables. Map() is often used to transform and process iterables without looping.
In this article, we learned how to use the map() method in Python by using several data types as examples.