Examples of using map() function in Python 3

Last updated on March 4, 2021 A Goodman Loading... Post a comment

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

Overview

Syntax:

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)
print(list(result))

Output:

[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)
print(list(correct_names))

Output:

['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)
print(tuple(result))

Output:

(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: VS Code: How to comment out a block of Python code, Examples of numpy.linspace() in Python, Extract all links from a webpage using Python and Beautiful Soup 4.

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles