All IT Courses 50% Off
Python Tutorials

Python map() function with EXAMPLES

Sometimes you have a list of inputs that need to be passed to a single function. The Python map function helps us do this task. For example, there is a list of numbers like [ 2, 3, 4, 6] and you want to find the square of all the numbers. There are two approaches to this. One is you iterate over the list and pass the number one by one to the function and then save the output one by one in the result list. And the other way is to use the map function. Let’s take a look at code.

numbers = [2, 3, 4, 6]

def square(x):
return x * x
print(map(square, numbers))
print(list(map(square, numbers)))

The following is the output.

Python map() function with EXAMPLES

Using map function with built-in functions

In the above example, we created our own square functions. Now let’s take a look at how Python map function works with built-in functions. Let’s take the factorial of all the numbers in a list.

import math
numbers = [2, 3, 4, 6]
print(map(math.factorial, numbers))
print(list(map(math.factorial, numbers)))
map function

Using map() with Tuple

Let us apply our map function on tuples.

def UpperCase(n):
return n.upper()
Name = ('john','brick')
updated_tuple = map(UpperCase, Name)
map function on tuples

Using map() with Lambda function

Let’s use the lambda function inside the map. These programming practices make it really easy to code.

numbers = [2, 3, 4, 6]
square = map(lambda x: x * 2, numbers)
lambda function
Facebook Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button

Get Python Course
worth 499$ for FREE!

Offer valid for 1st 20 seats only, Hurry up!!

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

H2kinfosys Blog will use the information you provide on this form to be in touch with you and to provide updates and marketing.