Examples of using map() function in Python 3
( 26 Articles)
In this article, we’ll go over a few examples of using the map() function in Python 3.
- 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.
In this example, we will write a short program to square the elements in a given list.
numbers = [1, 2, 3, 4, 5] def square(x): return x ** 2 result = map(square, numbers) print(list(result))
[1, 4, 9, 16, 25]
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.
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))
['Bobby Axelrod', 'Chuck Rothes', 'Wendy Rothes', 'Bry Connety', 'Taylor Manson', 'Kindacode']
In this example, we’ll use map() with the lambda expressions.
The program below calculates the length of each word in a given tuple.
words = ('dog', 'cat', 'dragon', 'building', 'Breaking Bad', 'Lord Of The Rings', 'End Game') result = map(lambda word: len(word), words) print(tuple(result))
(3, 3, 6, 8, 12, 17, 8)
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.