Python

Python map function Example

Hello in this tutorial, we will understand the different ways to use the map function in python programming.

1. Introduction

The map() function in python programming executes a given function for each item in an iterable. The entity to the function is sent as a parameter. Following the syntax for the map() function –

1
2
3
4
map(function, iterables)
where,
function - Is a mandatory parameter that denotes the function to be executed for each item
iterable – Is a mandatory parameter that represents a sequence, collection, or an iterator object

1.1 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. Python map function Example

I am using JetBrains PyCharm as my preferred IDE. You are free to choose the IDE of their choice.

2.1 Use map() function

Let us understand this with the help of a code snippet.

Use map() function

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
# map() function returns a map iterator object of the results after applying the giving function to each item
# of a given iterable
# Syntax - map(function. iterator)
def add(x):
    return x + x
def multiply(x):
    return x * x
numbers = (1, 2, 3, 4, 5)
addition = map(add, numbers)
print(list(addition))
multiplication = map(multiply, numbers)
print(list(multiplication))
# map() function with lambda expression
lambda_result = map(lambda x: x * x, numbers)
print('\nmap() with Lambda expression')
print(list(lambda_result))

If everything goes well the following output will be shown in the IDE console.

Console Output

1
2
3
4
[2, 4, 6, 8, 10]
[1, 4, 9, 16, 25]
map() with Lambda expression
[1, 4, 9, 16, 25]

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned –

  • An introduction to map() function in the python programming language
  • Sample program to understand the map() function in the python programming language

You can download the source code of this tutorial from the Downloads section.

4. Download the Project

This was an example of map() function in python programming.

Download
You can download the full source code of this example here: Python map function Example

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button