Definition and Usage
The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.
Python map() function
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:
[pastacode lang=”python” manual=”map(fun%2C%20iter)” message=”” highlight=”” provider=”manual”/]
Parameter
- 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 :
[pastacode lang=”bash” manual=”Returns%20a%20list%20of%20the%20results%20after%20applying%20the%20given%20function%20%20%0Ato%20each%20item%20of%20a%20given%20iterable%20(list%2C%20tuple%20etc.)%20%0A” message=”” highlight=”” provider=”manual”/]
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) .
Example 1:
[pastacode lang=”python” manual=”%23%20Double%20all%20numbers%20using%20map%20and%20lambda%20%0A%20%20%0Anumbers%20%3D%20(2%2C%204%2C%206%2C%208)%20%0Aresult%20%3D%20map(lambda%20x%3A%20x%20%2B%20x%2C%20numbers)%20%0Aprint(list(result))%20%0A%0A” message=”” highlight=”” provider=”manual”/]
Output:
[pastacode lang=”bash” manual=”%5B4%2C%208%2C%2012%2C%2016%5D” message=”” highlight=”” provider=”manual”/]
Example 2:
[pastacode lang=”python” manual=”%23%20List%20of%20strings%20%0Al%20%3D%20%5B%E2%80%98wikitechy%E2%80%99%2C%20%E2%80%98wiki%E2%80%99%5D%20%0A%20%20%0A%23%20map()%20can%20listify%20the%20list%20of%20strings%20individually%20%0Atest%20%3D%20list(map(list%2C%20l))%20%0Aprint(test)%0A” message=”” highlight=”” provider=”manual”/]
Output:
[pastacode lang=”bash” manual=”%5B%5B%E2%80%98w%E2%80%99%2C%20%E2%80%98i%E2%80%99%2C%20%E2%80%98k%E2%80%99%2C%20%E2%80%98i%E2%80%99%2C%20%E2%80%98t%E2%80%99%2C%20%E2%80%98e%E2%80%99%2C%20%E2%80%98c%E2%80%99%2C%20%E2%80%98k%E2%80%99%2C%20%E2%80%98y%E2%80%99%5D%2C%20%5B%E2%80%98w%E2%80%99%2C%20%E2%80%98i%E2%80%99%2C%20%E2%80%98k%E2%80%99%2C%20%E2%80%98i%E2%80%99%5D%5D” message=”” highlight=”” provider=”manual”/]
Example 3:
[pastacode lang=”python” manual=”%23%20Python%20program%20to%20demonstrate%20working%20%0A%23%20of%20map.%20%0A%20%20%0A%23%20Return%20double%20of%20n%20%0Adef%20addition(n)%3A%20%0A%20%20%20%20return%20n%20%2B%20n%20%0A%20%20%0A%23%20We%20double%20all%20numbers%20using%20map()%20%0Anumbers%20%3D%20(2%2C%204%2C%206%2C%208)%20%0Aresult%20%3D%20map(addition%2C%20numbers)%20%0Aprint(list(result))%0A%0A” message=”” highlight=”” provider=”manual”/]
Output:
[pastacode lang=”bash” manual=”%5B4%2C%208%2C%2012%2C%2016%5D” message=”” highlight=”” provider=”manual”/]