Examples of using map() function in Python 3

Last updated on March 26, 2022 A Goodman Loading... Post a comment

In this article, we’ll go over a few examples of using the map() function in Python 3.



map(function, iterables)
  • function: The function to execute for each item
  • iterables: one or many iterables (lists, tuples, etc).

The map() function makes an iterator that computes the function using arguments from each of the iterables. It will stop when the shortest iterable is exhausted.

The map() function doesn’t change the input iterables but returns new map objects.

Example 1

In this example, we will write a short program to square the elements in a given list.

The code:

numbers = [1, 2, 3, 4, 5]
def square(x):
    return x ** 2

result = map(square, numbers)


[1, 4, 9, 16, 25]

Example 2

Suppose we have a list of the first and last names of several people. However, the writer of this list, in a hurry, was not careful and did not know the capitalization of some names. Our job is to write a Python program to correct those names.

The code:

names = ['bobby axelrod', 'chuck rothes',
         'wendy rothes', 'bry connety', 'taylor manson', 'kindacode']

def to_cap(name):
    return name.title()

correct_names = map(to_cap, names)


['Bobby Axelrod', 'Chuck Rothes', 'Wendy Rothes', 'Bry Connety', 'Taylor Manson', 'Kindacode']

Example 3

In this example, we’ll use map() with the lambda expressions.

The program below calculates the length of each word in a given tuple.

The code:

words = ('dog', 'cat', 'dragon', 'building',
         'Breaking Bad', 'Lord Of The Rings', 'End Game')

result = map(lambda word: len(word), words)


(3, 3, 6, 8, 12, 17, 8)

See also: Examples of using Lambda Functions in Python 3

Final Words

We have walked through a few examples of using the map() function in Python. This function is useful in many situations and lets us write cleaner and neater code.

If you would like to learn more interesting stuff about Python, take a look at the following articles:

You can also check out our Python category page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles