Python map() – Explained with example
Python includes a built-in method of applying a specific function to all elements within an iterable object: map()
. The Python map() method executes a function on all elements within an iterable object, such as a list, and returns map objects. The item is sent to the function as a parameter.
Syntax
map(function,iterables)
Map() Parameter
function
: map() passes each item of the iterable to this function.- iterable: This is a required parameter. A sequence, collection, or an iterator object. You can send as many iterables as you like, just make sure the function has one parameter for each iterable.
Map Examples
Example 1
Let’s write a simple map function that will calculate the length of Each name in the length of each word in the tuple:
def findLengthOfNames(a):
return len(a)
x = map(findLengthOfNames, ('wisdom', 'James', 'Deven','Favour'))
print(list(x)) #[6,5,5,6]
Example 2
Lets write another function that will calculate the square of multiple numbers:
def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result) #[1, 4, 9, 16]
Using lambda function with map()
Basically, A lambda function is a function without a name. Since the map()
the method expects a function to be passed in, lambda functions are commonly used while working with map()
functions.
numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result) #[1, 4, 9, 16]
Conclusion
Using things like for-loops, are often easier to keep correct. Map meanwhile has benefits in programs. Entire programs can be designed around it.