Python offers different built in functions to performs operations on data. One such function offered is map() function.
In python map() function is used to execute a each item in particular iteration.
Syntax:
map(fun, item)
function: the function is used to execute each item.
item: item in this tutorial referred has iterables there is no limit on passing the number of items, just make sure that function has one parameter for each items.
Example:
In the below function we are using the sum function two twice the numbers which is declared in the following function.
def sum(n): return n + n numbers=(2,2,2) result=map(sum, numbers) print(list(result)) Output: [4,4,4]
Adding two list using lambda and map() function:
In the below example we are defining the two list and adding those two list using the map and lambda function.
a1=[1,2,3] a2=[5,6,7] result=map(lambda x, y : x + y, a1,a2) print(list(result)) Output: [6,8,10]
if statement with map() function:
In below function we are using double_odd() function to double the odd values in the given list.
def double_odd(n): if n%2!=0: return n else: return n*2 num=[2,3,4,1,5] result=list(map(double_odd, num)) print(result) Output: [2,6,4,2,10]