Hello folks.....!!!
Today we will look at the predefined function
map()
map() function
It is used to apply a specific function on every element in an iterable. The syntax is given below:
map(function,iterable)
The map()
takes 2 parameters. The first one is a function. It can be a built-in
function or user defined one. Lambda functions are also allowed to be the
function parameter. The iterables in python like lists or strings is the
next parameter. The output cannot be used directly. Thus it has to be
converted into a usable iterable.
We shall look into some examples now for better understanding.
Example 1:
Simple built-in function
Convert the characters in the list to integers.
Example 2: User defined function utilization
Concatenate a '*' at the end of each character in the list.
Example 3: lambda functions
Consider a list of integers. Add 6 to each of the element.
You can pass any number of iterables. The function must be designed accordingly. Look at the example below.
Example 4: Two iterables
Find the length of each word in the list without using a for loop.
The buit-in function 'len' can be used here to find the length of each string within the list.
Example 6: filter() and map() combo
You have a list containing both Strings and integers. Desired output is a new list containing only the
square of the numbers. Look at the code below which is explained step by
step.
Step 1: The list is : li=[3,5,7,'apple','gate',9,'lizard',4,6]
Step 2: finding the square part using lambda function : lambda x:x**2
Step 3: filtration part : list(filter(lambda x:type(x)!=str,li))
Step 4: mapping part : list(map(step2,step3))
The consolidated code is :
Exercises:
1. para="Sir Isaac Newton PRS was an English mathematician, physicist, astronomer, theologian, and author who is widely recognized as one of the most influential scientists of all time and as a key figure in the scientific revolution."
Find out the lengthiest word in the paragraph. Use appropriate functions.
2. li1=['be','fi','sca','ri','con','di']
li2=['st','ne','ry','se','text','sk']
Concatenate the lists to form meaningful words.
3. li=[23,5,78,3,23,45,6,90,2,4,76,8]
Create a new list which contains the cube of the numbers less than 25 in the list give above.
Next Topic👉
Comments
Post a Comment