Python map() – This method returns a map object(which is basically an iterator) of the results or answers after applying the given function to each and every item of a given iterable, it can be a list, tuple, etc.
SYNTAX –
map(givenFunc, givenIter)
where,
- givenFunc – It is the function to which the map passes each element of a given iterable. It is a mandatory field.
- givenIter – It is basically a sequence, collection or any iterator object. We can send as many iterables as we like. It is also a mandatory field.
Map() return value –
The map() method or function returns an object of the map class. The returned value can be passed to any function like
- list() – to convert it to a simple list
- set() – to convert it to a set
For example –
Make new words by adding words from two different iterable objects:
def func(a,b):
return a+b
x = map(func,(‘tech’, ‘bread’, ‘food’ ), (‘study’, ‘jam’, ‘study’ ) )
OUTPUT –
[‘techstudy’,’breadjam’,’foodstudy’]
NOTE: Lambda function – A lambda Python map function is basically a short function that doesn’t have a name.
Using lambda function with map –
Code:
numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
OUTPUT :
[16, 1, 4, 9]