The map() in Python is a built-in function. For each item of the iterable (e.g. list, tuple, etc.), the map() calls the defined function and returns a list of results. The first argument in the map() is that you need to pass a function without calling it. This means that there are no parentheses.
The operation performed by map() is usually known as a mapping, as it maps every item in an iterable input to an iterable new item. This is achieved by applying map() to all things in the input iterable.
Check out the details on Self in Python!
Python uses the map concept from functional programming. The map operation considers the mapping function and the data vector as arguments and returns the new vector, which results in the development of the mapping function on each vector object.
Syntax:
The syntax of map() in python is:
map(function, iterable)
Let’s assume that you want to use a list of operations or functions to construct a new list for each variable and use those outputs. An example would be to have a list of numbers and to create a new list with their cubes. One way to do this is by going through the list of numbers you are using for loop, and using a function that returns the cube of each number or part.
Following is a simple program using the map function in python that returns the cube of a number:
# defining a function that returns the cube of a number
def cube(number):
return number**3
# original list
number_list = [1,2,3,4,5,6]
# list that will contain the squared numbers
number_list_cube = []
# using a for loop to iterate over our number_list and create a new list with the cubic values
for number in number_list:
number_list_cube.append(cube(number))
print(number_list_cube)
#
output
[1,4,9,16,25,36
We have a list of numbers, number_list, and we want to create a new list, number_list_cube, that contains the squares of number_list. We use a for loop to loop over number_list, and append the square of each number or number to our number_list_cube list.
The built-in python function called map is another way to do this. There are two arguments in the map function: the function we want to apply and the object or sequence to which we want to apply it (such as a list in this case). In other words, the map function maps or applies it to each element in the sequence.
Working of map() function in Python:
Two inputs as a function and an iterable object used by the map(). The function given to map() is a normal function and is iterated over all the values in the given object.
For example, making a list of numbers, and finding the cube for each number.
The function is required that will return the double of the number. The function will be as follows:
def double(number):
return number+number
Now we will create the list of items:
number_list = [1,2,3,4,5]
Now we will use the map() function to find the double of each item in the number-list.
def double(number):
return number*2
number_list = [1,2,3,4,5]
number_list = map(double, number_list)
print(list(number_list))
Output:
[2, 4, 6, 8, 10]
We have used list() in the code to iterate the output from the map. The map() function helps to get the double of each number.
map() in Python with built-in functions:
The map() in Python is a built-in function and can also be used with other built-in functions available in Python. In the example, we are going to make use of the Python pow() built-in function. It is given to map two list objects, one for each base and index parameter. The result is a list containing the power of each number in bases raised to the corresponding number in the index.
Example:
We have two lists, one is base and another is index.
base= [10, 20, 30, 40, 50]
index= [1, 2, 3, 4, 5]
We will use pow() as the function to map().
base=[10, 20, 30, 40, 50]
index=[1, 2, 3, 4, 5]
powers=list(map(pow, base, index))
print(list(powers))
Output:
[10, 400, 27000, 2560000, 312500000]
map() in Python with Tuple:
Tuples in Python are an ordered collection of objects. They are defined by enclosing the elements in parentheses (()). In certain instances, the tuple is identical to the list in terms of indexing, nested objects and repetition, but the tuple is immutable, unlike the lists.
Even though tuples are defined using brackets, you still use square brackets to index and slice tuples, just like strings and lists.
Example:
In the following example we will use the function that will convert the values of the tuple into uppercase.
def upperFunc(values):
return values.upper()
values_tuple = ('swift','java','python','go','kotlin')
new_list = map(upperFunc, values_tuple)
print(list(new_list))
Output:
['SWIFT', 'JAVA', 'PYTHON', 'GO', 'KOTLIN']
map() in Python with Dictionary:
Dictionaries are the implementation by Python that is more generally known as an associative array. A dictionary is a collection of key-value pairs. It is defined by curly brackets({}).
Dictionaries are both mutable and dynamic. They can be updated and deleted as needed. Dictionaries differ from lists as Dictionary elements are accessed via keys while List elements are accessed by their position in the list, via indexing.
The dictionary is an iterator, you can use it inside the map() function.
Example:
def dictFunc(values):
return values*10
values_dict = {1,2,3,4,5}
finalitems = map(dictFunc, values_dict)
print(list(finalitems))
Output:
[10, 20, 30, 40, 50]
map() in Python with Set:
Sets in Python are unordered, and the elements of a set are unique i.e. they cannot be the same. You can modify a set, but the elements in the set must be immutable. Like dictionary set() is also an iterator, you can use it inside the map() function.
Example:
def setFunc(values):
return values*10
values_set = {1,2,3,4,5}
finalitems = map(setFunc, values_set)
print(list(finalitems))
Output:
[10, 20, 30, 40, 50]
map() in Python with Lambda function:
A Lambda Function is an anonymous function that means a function without a name. A Lambda function contains multiple arguments with one expression.
We use the def keyword to define a normal function in Python. Similarly, we use the lambda keyword to define an anonymous function in Python. Lambda functions are syntactically restricted to a single expression.
We can use the lambda function inside the map() function in Python.
Example:
numbers = (1,2,3,4,5)
result = map(lambda x: x+x, numbers)
print(list(result))
Output:
[2, 4, 6, 8, 10]
map() in Python with Other Functional Tools:
We can perform more complex transformations on iterables by using map() together with functional tools like filter() and reduce().
map() and filter():
In some problems we need to process an input iterable and return another iterable by filtering unnecessary values in an iterable input. The filter() of Python is a good choice in this situation.
Filter() returns the iterable input items for which the function returns true. If no function is passed, filter() uses the identity function. This implies filter() monitors each item in iterable for its true value and filters all falsy items out.
Example:
If we want to calculate the square root of all the values in a list and if our list have negative values, we’ll get an error because the square root isn’t defined for negative numbers. In order to prevent this problem, filter() is used to filter out all negative values and then find the square root of the remaining positive values.
import math
def is_positive(num):
return num >= 0
def filtered_sqrt(numbers):
filtered_iter = map(math.sqrt, filter(is_positive, numbers))
return list(filtered_iter)
filtered_sqrt([100, 9, 225, -36, 0])
map() and reduce():
Another function that exists in functool module of Python is reduce() in the standard library of Python. Reduce() is another key functional method in Python that is helpful when an iterable feature needs to be added to and reduced to a single cumulative value. This form of action is generally called reducing or folding.
Example:
We will use map() and reduce() to calculate the total size of all the files that live in your home directory.
import functools
import operator
import os
import os.path
files = os.listdir(os.path.expanduser(“~”))
functools.reduce(operator.add, map(os.path.getsize, files))
We will call os.path.expanduser("~") to get the path to your home directory. Then you call os.listdir() on that path to get a list with the paths of all the files that live there. The call to map() uses os.path.getsize() to get the size of each file. You eventually use reduce() to obtain the total sum of the size of each file using operator.add(). The end result is the total file size in bytes of your home directory.
Top Cities Where KnowledgeHut Conduct Python Certification Course Online
Generator Expressions instead of map() in Python:
map() in python returns a map object, an iterator that returns items on request. The natural substitution for map() is therefore a generator expression. Generator expressions return generator objects, which are also iterators, which yield items on request.
A tiny difference occurs between a list comprehension and a generator expression. The list uses a pair of square brackets ([]) while generator expressions use a pair of parentheses (()). If you want to turn a list comprehension into a generator expression, you just need to replace the square brackets with parentheses.
def square(number):
return number ** 2
numbers = [1, 2, 3, 4, 5]
gen_exp = (square(x) for x in numbers)
print(list(gen_exp))
Output:
[1, 4, 9, 16, 25]
Generator expressions are commonly used as arguments in function calls.
Conclusion:
map() in python allows to perform operations on iterables. Map() usually helps you to convert and process iterables without directly using a loop.
Python map() is a built-in-function that applies a function to all the input items of an iterator. For example, a list, tuple, etc. can be an iterator, and it returns a map object that can be iterated. The map() function will add all the items inside the iterator to the specified function, and then return an iterable map object, i.e. tuple, list, etc. map() in Python is an embedded function that can also be used in Python with other integrated functions.