The built-in function map() helps to execute the given function to each and every element of a specified iterable (list, tuple, set, dictionary, string, etc.) and returns a list of the results.
map(function, iterable, ...) #where iterable can be list, tuple etc
Takes two parameters. We can pass multiple iterator objects to map() function in such case, the given function must have that many arguments.
| Parameter | Description | Required / Optional |
|---|---|---|
| function | The function to be called for each element of the specified iterable. | Required |
| iterable | iterable which is to be mapped | Required |
The returned value from map() (map object) can then be passed to functions like list() (to create a list), set() (to create a set) and so on.
| Input | Return Value |
|---|---|
| iterable | iterator object of the map class |
def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
Output:
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:
num1 = [4, 5, 6]
num2 = [5, 6, 7]
result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))
Output:
[9, 11, 13]
# map() with string
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)
Output:
A B C