Map Syntax in Python
Introduction:
In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you want to transform each iterable element using a single transformation function, you use it. In Python, the map receives the iterable and the function as parameters.
Python's Map syntax
The Python map() function's syntax is as follows:
map(function, iterables)
In the earlier syntax:
- function: This is where all of the iterable's items will pass through in order to be transformed.
- Iterables: The object you want to map is an iterable (a sequence, collection like a list, or tuple).
In order to better comprehend the Python map syntax, let's look at an example. The following code first generates a list of numbers before multiplying each one by itself using the Python map() method.
Code:
# A function's definition
def multi(a):
return a * a
# Utilizing the map feature
var = map(multi, (2, 4, 6, 8, 10, 12, 14, 16))
print (var)
print(list(var))
Output:
[Running] python -u "d:\Programming\Python\test.py"
<map object at 0x0000019934CABD90>
[4, 16, 36, 64, 100, 144, 196, 256]
[Done] exited with code=0 in 0.406 seconds
The map object was printed in its entirety by the first print function, as shown in the code above. To make the map object readable, you must transform it into a list, set, or other iterable items.
How the Python Map() Method Works
Python's map function accepts a function and an iterable or iterable. The transformation function is applied while iterating through each item in an iterable. The value of the converted item is then stored in a map object, which is then returned.
Any callable method, including built-in, lambda, user-defined, classes, and methods, may be used as the input function. Now, in order to better grasp how the map() function functions, compute the same multiplication as you did in the prior example, but this time using both the for loop as well as the map functions independently.
Example: Utilizing for loop:
number = [2, 4, 8, 10, 12, 14, 16]
multi = []
for i in number:
multi.append (i ** 2)
print (multi)
Output:
[Running] python -u "d:\Programming\Python\tempCodeRunnerFile.py"
[4, 16, 64, 100, 144, 196, 256]
[Done] exited with code=0 in 0.384 seconds
Example: Using the Map() function in Python:
def multi(a):
return a * a
number = (2, 4, 6, 8, 10, 12, 14, 16)
rslt = map(multi, number)
print (rslt)
# creating a readable map object
result_of_multi = list(rslt)
print (result_of_multi)
Output:
[Running] python -u "d:\Programming\Python\test.py"
<map object at 0x000001537BF6BD90>
[4, 16, 36, 64, 100, 144, 196, 256]
[Done] exited with code=0 in 0.358 seconds
You can see that, like the for loop, the map() function loops through the iterable. The map object is returned at the end of the loop. The map object can then be turned into a list and printed.
You may have also noted that this time when utilizing the map function in Python, you specified the iterable independently before passing it to the function. So, you have the option of defining the iterable either individually or as part of the map() function.
Using Python's built-in Functions with Map
Additionally, you can use pre-defined built-in functions with the map() method in Python. Watch this in action now.
Example: Utilizing Map() function with Len() function
exmpl = ["Utilizing", "Map()", "function", "with", "Len()", "function"]
s = list(map(len, exmpl))
print(s)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[9, 5, 8, 4, 5, 8]
[Done] exited with code=0 in 0.327 seconds
Example: Utilizing Map with Math.Sqrt() function in python
To utilize Python's math.sqrt() function with map, firstly import the math library as shown in the example below.
import math
number = [4, 16, 36, 64, 100, 144, 196, 256]
n = list(map(math.sqrt, number))
# Display the value of n
print (n)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0]
[Done] exited with code=0 in 0.309 seconds
You can utilize any built-in methods with the map in Python, just like in the examples above.
Using Python's Map with Lambda Functions
The lambda functions are among the most typical use cases for the map function that you might come across. Lambda functions are anonymous, or nameless, functions. You can define the function directly within the map() function using the lambda function. Let's examine a sample to see how the lambda functions and the Python map() method are combined.
Example: Utilizing Map() function with Lambda() function:
You will utilize a lambda function in the code provided below to use the map function to double the integers in the iterable.
number = (7, 9, 3, 6 , 22, 55)
rslt = map(lambda j: j + j, number)
# Display the new list
print (list (rslt))
Output:
[Running] python -u "d:\Programming\Python\test.py"
[14, 18, 6, 12, 44, 110]
[Done] exited with code=0 in 0.289 seconds
How to Use a Map as an Iterator in Python
A String can be used with the map() method in Python. When a String is used with map(), it behaves like an array. The map() function can then be used as an iterator to cycle through every character in a string. To see it in action, let's look at an example.
Example: Using Map as an Iterator in Python:
def upper_case(a):
return a.upper()
str = "This is a simple example"
up_list = map (upper_case, str)
print (up_list)
# Display the list in upper case
print (list(up_list))
Output:
[Running] python -u "d:\Programming\Python\test.py"
<map object at 0x00000211D4C6BDF0>
['T', 'H', 'I', 'S', ' ', 'I', 'S', ' ', 'A', ' ', 'S', 'I', 'M', 'P', 'L', 'E', ' ', 'E', 'X', 'A', 'M', 'P', 'L', 'E']
[Done] exited with code=0 in 0.337 seconds
How to Use Map() with Tuple
You will need a tuple with some string values to complete this code. The function to transform the strings to the upper case will then be defined. Finally, in order to use the tuple and the method to change the string values to uppercase, you must utilize the map in Python.
Example: Map() function with Tuple
def Truple_example(a):
return a.upper()
Tuple = ('This', 'is', 'a', 'simple', 'example', 'of', 'Map', 'function')
up_tup = map(Truple_example, Tuple)
print(up_tup)
print(tuple(up_tup))
Output:
[Running] python -u "d:\Programming\Python\test.py"
<map object at 0x0000027106B6BDF0>
('THIS', 'IS', 'A', 'SIMPLE', 'EXAMPLE', 'OF', 'MAP', 'FUNCTION')
[Done] exited with code=0 in 0.264 seconds
Using a Dictionary and Map in Python:
Another form of collection that holds key:value pairs in Python is a dictionary. A dictionary can be defined using curly brackets. In the example that follows, you will utilize a dictionary of car names and the map() function to append a '_' to the end of each name. You can see that this example made use of a lambda function.
Example: Utilizing Map() function with dictionary
car_dictionary ={'a': 'Lamborghini', 'b': 'BMW', 'c': 'Mercedes-Benz', 'd': 'Ferrari', 'e': 'Jeep'}
# '_' is added to the end of each value.
car_dictionary = dict(map(lambda a: (a[0], a[1] + '_'), car_dictionary.items() ))
print ('The updated dictionary\'s name is : ')
# Display the car dictionary
print (car_dictionary)
Output:
[Running] python -u "d:\Programming\Python\test.py"
The updated dictionary's name is :
{'a': 'Lamborghini_', 'b': 'BMW_', 'c': 'Mercedes-Benz_', 'd': 'Ferrari_', 'e': 'Jeep_'}
[Done] exited with code=0 in 0.356 seconds
Using Map() With Set
The Python map() function allows you to use a set in a manner similar to other iterables. In the sample example below, you must establish a collection of numbers and display the remainder of each value after dividing by three.
Example: Utilizing Map() function with set:
def Set_example(j):
return j%4
Set= {45, 23, 67, 102, 112, 20, 23, 44}
up_itms = map(Set_example, Set)
print (up_itms)
print (set (up_itms))
Output:
[Running] python -u "d:\Programming\Python\test.py"
<map object at 0x00000262DC56BDC0>
{0, 1, 2, 3}
[Done] exited with code=0 in 0.282 seconds
Conclusion
- The built-in method map() in Python applies a function to each item in an input iterator. An iterator returns an iterable map object and can, for instance, be a list, a tuple, a string, etc.
- The map() method will apply the specified function to each item in the iterator and produce a tuple, list, or other iterable map objects.
- The built-in map() function in Python can be used with other built-in methods to create new functions.
- Python objects with items surrounded in round brackets and separated by commas are known as tuples.
- Curly brackets() are used to generate a dictionary in Python. You can use the dictionary inside the map() function because it is an iterator.
- A set in Python is a group of elements enclosed in curly brackets ({}). You can use set() inside the map() function because it is also an iterator.
- In Python, anonymous functions are created using lambda expressions (also known as lambda forms). Therefore, if you wish to utilize lambda inside the map, you must use the lambda keyword ().
- You can use the map() function to communicate several iterators, such as a list or tuple.