Introduction
The map() function in Python is used to return the result as a map object without using an explicit for loop. It can handle iteration without a loop.
This is a useful function that allows you to apply a transformation function to each item of a given iterable. Below is the guide on how to use the map() function in Python as we go through below.
Example
We have some command lines:
def func(n): return len(n) x = map(func, ('cat', 'dog', 'tiger')) print(x) print(list(x))
Output:
<map object at 0x00000000020E7940>
[3, 3, 5]
Definition
The map() function executes a specified function for each item in an iterable file. Item in function as a parameter.
The syntax
map (function, iterables)
Parameter Values:
function: The function executes for each element in the iterable
iterables: a list, tuple, dictionary… want to browse
More examples
Example 1: Double the variable value n:
def calc(n): #Double n return n + n numbers = (2, 4, 6, 8) result = map(calc, numbers) #Convert map object to list print(list(result))
Output:
[4, 8, 12, 16]
Example 2: Using lambda function with map():
numbers = (2, 4, 6, 8) result = map(lambda n: n+n, numbers) print(list(result))
Output:
[4, 8, 12, 16]
Example 3: Passing multiple iterator parameters to map() using lambda:
num1 = [2, 3, 4] num2 = [4, 5, 6] result = map(lambda x, y: x + y, num1, num2) print(list(result))
Output:
[6, 8, 10]
Conclusion
You have just seen detailed instructions on how to use the map() function in Python.
Thank you for reading.