ADVERTISEMENT
ADVERTISEMENT

Python map() Function with Examples

Learn about the map() function, its usages, syntax, and examples.
Submitted by IncludeHelp, on March 06, 2022

In Python programming language, the map() function is a built-in function that 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 for map() function:

map(function, iterable_type)

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 of map() function: The map() function returns a list of the results after applying the given function to each item of a given iterable.

Example 1:

# 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]

Example 2: An example of using of lambda expressions 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]

Example 3:

# 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]
ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.