maps function in Python

After the application of the given function to each item of a given iterable, the map() function returns a map object (which is an iterator) of the results (list, tuple, etc.).

Despite being predominantly an object-oriented programming language, Python has several functional programming features. The map() method is maybe the most notable. The application of a function to each item in an iterable, use the map() function, a Python built-in function like a Python list or dictionary. It returns a new iterable such as a map object that you can use elsewhere in your program. Python’s map() function is a built-in function that combines with other Python built-in functions.

maps function in Python

The map() function performs a specified process for every single item in an iterable. In addition, the item is passed as a parameter to the procedure.

The syntax is as follows:

map(fun, iter)

The following are the maps() parameters:

  • fun: It’s a function that the map uses to pass each element of an iterable to.
  • iter: It’s iterable that has to be mapped. An Iterable is a must. An object is either a series, a collection, or an iterator. You can send as many iterables as you like; make sure each iterable has its parameter in the method.

The map() function accepts one or more iterables.

Returns:

After applying the supplied function to each item of a given iterable, it returns a list of the results (list, tuple, etc.). The value returned can be used in functions like:

  • list() – To convert to a list, use the list() function.
  • Set() – is used to change a variable to a set, and so on.

NOTE: The map() (map object) returned value can then be provided to functions like list() (to build a list) and set() (to construct a set).

Example: program demonstrating the working of map()

# Python program to demonstrate working
# of the map.

# Return double of n
def addition(n):
	return n + n

# We double all numbers using map()
numbers = (3, 4, 5, 6)
result = map(addition, numbers)
print(list(result))

We may also utilize lambda expressions with a map to get the above outcome.

# Using map and lambda, double all numbers

numbers = (1, 2, 3, 4)

result = map(lambda x: x + x, numbers)

print(list(result))

Example: Using map and lambda, combine two lists

num_vals1 = [1, 2, 3]
num_vals2 = [4, 5, 6]

final_result = map(lambda x, y: x + y, num_vals1, num_vals2)

print(list(final_result))

Example: List of strings

string_list = ['dat','dad', 'bat', 'cat', 'mat']

# map() can listify the list of strings individually

list_vals = list(map(list, string_list))
print(list_vals)

Example: Determine the length of each of the tuple’s words

def codefunc(n):
  return len(n)

x = map(codefunc, ('Apple', 'Chromebook', 'HP'))

Example: Send two iterable objects into the function to create new fruits

def codefunc(a, b):
  return a + b

x = map(codefunc, ('Apple', 'Chromebook', 'IBM'), ('DELL', 'HP', 'Lenovo'))

The map() function produces an iterator after applying a provided process to each item of an iterable (list, tuple, etc.).

num_vals = [2, 4, 6, 8, 10]

# method is responsible for returning the numbers' square

def NumSquare(val):
  return val * val
# apply NumSquare() function to each item of the numbers list
squared_nums_iterator = map(NumSquare, numbers)
# converting to a resultant list
list_of_squared_numbers = list(squared_nums_iterator)
print(list_of_squared_numbers)
# Output: [24, 36, 56, 84, 120]

Example: pass one tuple and a list iterator to a map() function

In the map() function, we will utilize a list and a tuple iterator. The function CodeMapFunc() is passed to the map, and it will retrieve the items from the list and the tuple. An underscore(_) is used to connect the components. The following is a working example:

def CodeMapFunc(list_one, tuple_one):
  return list_one+"_"+tuple_one

code_list = ['a','b', 'b', 'd', 'e']
language_tuple = ('Kotlin','JavaScript','PHP','Java','Ruby','Python','C++','C')
code_updated_list = map(CodeMapFunc, code_list,language_tuple)

print(code_updated_list)
print(list(code_updated_list))

Example: Using two iterators in a list to map ()

You can provide many iterators to the map() function at once – such as a list, a tuple, etc. For instance, suppose you want to combine two lists. The map() function is used to accomplish the same thing. code_list_one and code_list_two are the two lists we’ll be using. The first item in code_list_one is added to the code_list_two first items in the example below.

CodeMapFunc() accepts elements from both code_list_one and code_list_two and returns the sum of the two. Here’s an example of using the map() method to combine two lists.

def CodeMapFunc(list_one, list_two):
    return list_one+list_two

code_list_one = [12,13,14,15,16,17,18,19]
code_list_two = [14,18,12,16,30,34,38]

code_updated_list = map(myMapFunc, code_list_one,code_list_two)
print(code_updated_list)
print(list(code_updated_list))

The use of functions with multiple iterables in Python

So far, we’ve just passed single-argument map() functions (recall the cube(num)). But what if your function accepts several parameters? The pow(x, y) function, which accepts two inputs and returns the result of x^y, is an example of this. After the first one, add another iterable name to apply a function with multiple arguments.

base = [11, 12, 13, 14]
power = [11, 12, 13, 14]

code_result = list(map(pow, base, power))

print(code_result )

Using map() in conjunction with Set

In Python, a set is an unordered list of things enclosed in curly brackets(()). You can use set() inside the map() function because it is also an iterator. Here’s an example of how to use a set as an iterator inside the map()

def CodeMapFunc(n):
    return n*100
code_set = {12,13,14,15,16,17,18,19}
final_code_items = map(myMapFunc, code_set)
print(final_code_items)
print(list(final_code_items))

Using map() as an iterator with a string

A string is also used with a map(). Because a string in Python behaves like an array, we can utilize it inside the map() with ease.

We have a CodeMapFunc () function in the example that converts the given string to uppercase. The map() function is provided the function CodeMapFunc(). By giving the string to CodeMapFunc, the map function will take care of changing the string to uppercase().

def CodeMapFunc(s):
    return s.upper()
code_str = "welcome to codeunderscored!"
code_updated_list = map(CodeMapFunc, code_str)
print(code_updated_list)
for i in code_updated_list:
    print(i, end="")

Lambda functions are typically used with map() functions since they need a process. A lambda function is an anonymous, short function. To learn more about the Python lambda function, go to this page.

Example: How to use lambda function with map()?

numbers = (6, 7, 8, 9)
result = map(lambda x: x*x, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

How to use Python’s built-in functions

Built-in Python functions are also used with the maps() function. If you have a list of strings, for example, you can quickly build a new list that has the lengths of each string in the list.

starter_list = ["Code", "programming", "in", "Codeunderscored"]
final_list = list(map(len, starter_list))
print(final_list )

We’ll utilize the Python round() built-in function to round the values provided in this example.

Example:

code_list = [22.6743,3.63526,24.2325,5.9687967,26.3265,27.6988,28.232,29.6907] is the list we have. For each item in the list, we need rounded values. The function we’ll use to map() will be round().

code_list = [22.6743,3.63526,24.2325,5.9687967,26.3265,27.6988,28.232,29.6907]
updated_code_list = map(round, code_list)
print(updated_code_list)
print(list(updated_code_list))

Using listof numbers with map()

To work with a list in the map(), take a list of numbers and multiply each by 100. We’ll use the following list: [12,13,14,15,16,17,18,19]. CodeMapFunc () is responsible for multiplying the given integer by a hundred. Along with the list, the function is passed to the map.

def CodeMapFunc(n):
    return n*100

code_list = [32,33,34,35,36,37,38,39]

code_updated_list = map(myMapFunc, code_list)
print(code_updated_list)
print(list(code_updated_list))

We can see in the result that each number in the list is 100 times multiplied.

Using tuple with map()

In Python, a tuple is a collection of things separated by commas and enclosed in round brackets. We’ll use a tuple containing string values as an example. We will use a function to change the given numbers to uppercase.

Example:

def CodeMapFunc(val):
    return val.upper()

code_languages = ('JavaScript','Python','Java','Kotlin','PHP','C')

updated_code_languages = map(myMapFunc, code_languages)
print(updated_code_languages)
print(list(updated_code_languages))

The result is a tuple in which all values have been transformed to uppercase.

Curly brackets({}) are used to generate a dictionary in Python. You can use the dictionary inside the map() function because it is an iterator. Now, inside the map() function, let’s utilize a dictionary as an iterator. The following example demonstrates how a dictionary iterator in a map() works.

def CodeMapFunc(n):
    return n*100
code_dict = {12,13,14,15,16,17,18,19}
final_code_items = map(myMapFunc, code_dict)
print(final_code_items)
print(list(final_code_items))

Final thoughts

In Python, the definition of a tuple is a representation of a collection of things separated by commas. It is also enclosed in round brackets. In this example, a tuple with string values is used. We used a function to change the given numbers to uppercase.

Curly brackets() are used to generate a dictionary in Python. You can use the dictionary inside the map() function because it is an iterator. Further, in Python, a set is an unordered list of things enclosed in curly brackets(()). You can use set() inside the map() function because it is also an iterator.

Lambda expressions (or lambda forms) are used to create anonymous functions in Python. When you want to utilize lambda inside the map(), you must use the lambda keyword. You can additionally use the map() function with multiple iterators, such as a list or a tuple.

In this article, you learned how to use the map() method in Python. You also saw how it might significantly reduce the bulk of your code, making it easier to read clean and bug-free code. You should now be able to use built-in functions, lambda expressions, and even your custom function with map().

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *