🧠 Second Brain

Search

Search IconIcon to open search

Python and Functional programming

Last updated Feb 9, 2024

# map()

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Syntax :

map(fun, iter)

Parameters :

fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.

NOTE : You can pass one or more iterable to the map() function.
Returns :

Returns a list of the results after applying the given function
to each item of a given iterable (list, tuple etc.)

 
NOTE : The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) .
 
CODE 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Python program to demonstrate working`
# of map.`
# Return double of n`
def` `addition(n):`
 return` `n` `+` `n`
# We double all numbers using map()`
numbers` `=` `(``1``,` `2``,` `3``,` `4``)`
result` `=` `map``(addition, numbers)`
print``(``list``(result))`

Output :
[2, 4, 6, 8]
   
**CODE 2**  
We can also use [lambda expressions](https://www.geeksforgeeks.org/python-lambda-anonymous-functions-filter-map-reduce/) with map to achieve above result.

`# Double all numbers using map and lambda`
`numbers` `=` `(``1``,` `2``,` `3``,` `4``)`
`result` `=` `map``(``lambda` `x: x` `+` `x, numbers)`
`print``(``list``(result))`

Output :
[2, 4, 6, 8]
   
**CODE 3**

`# Add two lists using map and lambda`
`numbers1` `=` `[``1``,` `2``,` `3``]`
`numbers2` `=` `[``4``,` `5``,` `6``]`
`result` `=` `map``(``lambda` `x, y: x` `+` `y, numbers1, numbers2)`
`print``(``list``(result))`

Output :
[5, 7, 9]
   
**CODE 4**
`# List of strings`
`l` `=` `[``'sat'``,` `'bat'``,` `'cat'``,` `'mat'``]`
`# map() can listify the list of strings individually`
`test` `=` `list``(``map``(``list``, l))`
`print``(test)`

Output :

[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]

Related Big-O


Origin:
References: Python Pluralsight course - Functional Programming with Python
Created: 2021-12-23