Python map() Method
In this tutorial, we will learn about the python map() method and its uses with examples.
What is the python map() method?
The map() method will return a map object of each item in an iterable. For example, (list, tuple, etc.)
These items are sent to the map method as a parameter.
The syntax of map() method is:
1
2
map(function, iterable)
map() parameters
The map() method takes two parameters as an argument.
- function - each item of the iterable will be passed to this function.
- iterable - A sequence or iterable object which is to be mapped.
Let’s see some examples of the map() method in python.
Example 1: Working of the Python map() Method?
1
2
3
4
5
6
def myfunc(a, b):
return a + b
x = map(myfunc, ('Tata', 'BMW', 'Audi'), ('Volkswagen', 'Porsche', 'Ford'))
print(x)
The output will be as follows.
1
2
<map object at 0x7fe0c0e9e4f0>
Since map() expects a method to be passed in, lambda methods are commonly used while working with map() methods.
A lambda method is a short method without a name. Visit this page to learn more about Python lambda methods.
Example 2: How to use the lambda method with map()?
1
2
3
4
5
6
7
8
numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
The output will be as follows.
1
2
3
<map 0x7fafc21ccb00>
{16, 1, 4, 9}
Rules of map() method
The map() method applies a given method to each item of an iterable and returns a list of the results.
The returned value from the map() (map object) can then be passed to methods like list() (to create a list), set() (to create a set), and so on.