Python map() function
Hi guys In this tutorial, we are going to learn what a map function does in python,
- The map is a built-in function in python.
- The map function (map() ), executes the specific function on each item of an iterable and returns the address of the map object.
Syntax of map() function in Python
Syntax : output= map(function_name,iter)
Parameters:
- function_name: It is a function to which map passes each element of given iterable.
- Iter: The iter can be a list, set, tuple, etc.
- You will get an output as a list by using list() inbuilt function
Note:.
- These two parameters are compulsorily required for the map function to execute.
- You can also give two or more iterable as parameters to a map function.
Examples of map() function
Now, let’s understand map function by using an example :
- Example 1:
#print the cubes of numbers passed a parameter in a list #cube is a function, It is defined in python as follows def cube(n): return (n*n*n) result=map(cube,[2,5,3]) print(list(result))
Output:
[8,125,27]
- Example 2:
# In this program 5 is subtracted from all the elements of number list by using subtract function def subtract(a): return(a-5) number=[25,81,400] result=map(subtract,number) print(list(result))
Output:
[20,76,395]
- Example 3 :
# In this program we add each element of number1 and number2 list by using add function def add(x,y): return(x+y) number1=[2,5,4] number2=[9,1,3] result=map(add,number1,number2) print(set(result))
Output:
{11, 6, 7}
Note:
- In the above code, we have given 2 iterable lists (number1, number2) as a parameter to a map function.
- The output we get as a set. Because of the set method used in the print method.
Example 4 :
# In this program concatenation of each element of number1 and number2 tuple done by using concatenate function def concatenate(x,y): return(x+y) number1=("Abhi","Vasu","John") number2=("Clever","Honest","Polite") result=map(concatenate,number1,number2) print(tuple(result))
Output :
('AbhiClever', 'VasuHonest', 'JohnPolite')
- Example 5:
number1=["143","How are you !"] result=map(list,number1) print(list(result))
Output :
[['1', '4', '3'], ['H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', ' ', '!']]
Note:
- In the above program, the list function is iterate on each element of the number1 list. Hence each element of number1 gets converted to a list.
- And since we print the result as a list, we get an output as a list.
Also read:
Leave a Reply