Python map() Function

Python Map() Function

Suppose, you have a Python list of items. The items here can be anything numbers, alphabets, words, etc. and you also have a function. You want to apply that function to each and every item of that list. Well, if you have options. You can just iterate the list using various loops like For, While, etc. and apply the function. But why to do so when we have a shortcut function for the same in Python?

It’s the Python map() function. The map function can apply any given function to an iterable (List, Tuple, etc.)

About the map() Method

  • Method Used – map()
  • What it Does – Apply the given function to specified iterable.
  • Number of Parameters it takes – 2 (Both are required)
  • Return Type – map() Type Object | Simply the Results which are obtained after applying the specified function.

Good To Know: You can combine the result obtained by applying the function on each iterable item using functions like list() and set(). Using the list() function, you can store the results into a Python List and similarly is the case for set() function. See the example for better understanding.

Example:

# Defined a Function that returns the number after adding five to it.
def addFive(n):
return n + 5
#Applying the map() Function
data = (1, 2, 3, 4, 5)
results = map(addFive, data)
print(list(results))

Output:

Python Map Function Example

Hope, you got a clear idea of the working of Python map() function with the above example.

More Examples

Some more typical examples of map() Function are given below.

An Example Using Lambda Expression

# Add 5 to all numbers using map and lambda
numbers = (1, 2, 3, 4, 5)
result = map(lambda x: x + 5, numbers)
print(list(result))

Output:

Python Map Function Example With Lambda Expression

An Example of Map Function Using Two Lists and Lambda Expression

# Multipying two lists with Corresponsing Elements using map and lambda
list1 = [1, 2, 3]
list2 = [4, 5, 6]
results = map(lambda x, y: x * y, list1, list2)
print(list(results))

Output

Python Map Function Example With Lambda Expression Applying On Two Lists

Thus, there could a lot of uses of the Python map() function.

Leave a Reply

Your email address will not be published. Required fields are marked *