Home »
Python »
Python Reference »
Python Built-in Functions
Python map() Function: Use, Syntax, and Examples
Python map() function: In this tutorial, we will learn about the map() function in Python with its use, syntax, parameters, returns type, and examples.
By IncludeHelp
Python map() Function
The map() function is a library function in Python, it is used to process and transform all the items in an iterable (list, tuple, dict, set) without using a for a loop. The 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.
Syntax
The following is the syntax of abs() function:
map(function, iterable_type)
Parameter(s):
The following are the parameter(s):
- function: Function for which the map() passes each element of the given iterable.
- iterable_type: It is an iterable type that is to be mapped.
Note: More than one iterables can be passed to the map() function.
Return Value
The map() function returns a list of the results after applying the given function to each item of a given iterable.
Python map() Example 1: Square of all numbers
# Python program to demonstrate the
# example of map() function
# Function to calculate the square
def square(n):
return n*n
# Using map() -
# finding the square of all numbers
values = (10, 20, 1, 5, 7)
print("The values: ", values)
squares = map(square, values)
print("The squares: ", list(squares))
Output
The values: (10, 20, 1, 5, 7)
The squares: [100, 400, 1, 25, 49]
Python map() Example 2: Use of lambda expression with map()
# Python program to demonstrate the
# example of map() function
# Using map() -
# finding the square of all numbers
values = (10, 20, 1, 5, 7)
print("The values: ", values)
squares = map(lambda n: n * n, values)
print("The squares: ", list(squares))
Output
The values: (10, 20, 1, 5, 7)
The squares: [100, 400, 1, 25, 49]
Python map() Example 3: Add two lists using map() and lambda expression
# Python program to demonstrate the
# example of map() function
# Adding two lists using map() and lambda
list1 = [10, 20, 30]
list2 = [11, 22, 33]
sum_lists = map(lambda m, n: m + n, list1, list2)
print("list1: ", list1)
print("list2: ", list2)
print("sum_lists: ", list(sum_lists))
Output
list1: [10, 20, 30]
list2: [11, 22, 33]
sum_lists: [21, 42, 63]