Python supports the functional programming paradigm that allows you to define tasks as a computation of functions programmatically. You can treat Python functions as objects: a function can take another function as a parameter and return another function. The map() function takes in a function as an argument and lets you apply it to all items in a sequence. By the end of this tutorial, you’ll be able to use the Python map() function — to rewrite verbose loops and list comprehensions. You’ll code several examples to understand the different ways you can use the map() function.
How to Apply a Function to Elements of a Python List
Let’s start our discussion with an example.👩🏫 Here nums is a list of numbers. Next, consider the function self_pow(). The function self_pow() takes in a number as the argument and returns the number raised to the power of the number itself: nn. In Python, ** is the exponentiation operator. ab returns the value of a raised to the power b, ab.
Using for Loop
To do this, you can use for loops in Python:
For every number in the nums list, call the function self_pow() with num as the argument. Append the result of the function call to the new list nums_pow.
In the output, every number nums is raised to itself. The elements in nums_pow list are as follows: 22, 44, 33,77.
Using List Comprehension
You can make this concise using list comprehension. From the explicit for loop above, we can identify the output expression, and the list to loop through. We can then modify the generic list comprehension expression: The list comprehension expression to generate the nums_pow list is as follows: The output is the same as that from using for loops, as expected. Instead of loop and list comprehension, you can use the Python map() function with a concise syntax that helps apply the function to all items in an iterable. Let’s start by learning the syntax of the map function.
Python map() Function Syntax
The general syntax to use the Python map() function is as follows: The map() function takes in at least two arguments, a function and an iterable. In the above syntax:
function denotes a Python function or in general, any Python callable. This includes user-defined and built-in functions, classes, instance and class methods, and more.iterable is any valid Python iterable, such as a list, tuple, and string. The map() function applies the function to every item in the iterable
What does the map() function return? It returns a map object. You can then cast the map object to a list using the syntax: list(map(function,iterable)). Depending on the use case, you can cast it into a Python tuple. Now that you’ve learned the syntax of the Python map() function, let’s start coding examples.
How to Use map() Function with User-Defined Functions
#1. Previously, we had applied the self_pow() function to every number in the nums list. In the syntax for map() function, we can pass in the function self_pow and the list nums as the arguments. Note: You should only specify the function’s name and not a function call. Use self_pow and not self_pow(). The map() function returns a map object. We can then cast the map object into a list using the list() function, as shown below. Here’s the output where every num in nums is mapped to numnum in nums_pow list. #2. Consider the following function inch_to_cm() that converts inches to centimeters. 1 inch = 2.54 cm. To convert the inch values in the inches list to centimeters, you can use the map() function as shown in the code cell below. The cms list contains the inch values expressed in centimeters.
How to Use map() Function with Built-In Functions
In this section, we’ll learn how to use map() with built-in functions in Python. #1. The list strings is a list of programming languages. You’d like to create a new list strings_upper that contains the programming language strings in uppercase. The list strings_upper includes strings in the list strings formatted in uppercase. #2. The built-in len() function in Python takes in a sequence as the argument and returns its length. To find the length of each of the strings in the strings list, we can use the map() function and apply the length function on each string, as shown below. #3. You can use the map() function with other collections such as tuples. The following example contains a tuple containing information on the number of bedrooms, area, and city in which a house is located. In Python, the type() function returns the datatype of any Python object. To get the datatype of all items in this tuple, you can use the map() function to call the type function on each tuple item. We’ve cast the map object into a tuple. You can also cast into a list or any other collection. In the output below, we see that the datatypes of 2, 758.5, and Bangalore, have been inferred as ‘int’, ‘float’, and ‘str’, respectively. #4. In Python, you can import built-in modules and use the functions defined in the modules. To compute the square root of every number in the nums list, you can use the square root function sqrt from the math module. The above output is difficult to parse and follow. You may want to round each square root value to say, two decimal places.
How to Round a Floating Point Number in Python
Let’s define a function round_2() that takes a floating point value and rounds it to two decimal places. Now, you can use the map() function with the round_2 and the nums_sqrt list. You can also use nested map() functions, where the inner map function is used to compute the square root list nums_sqrt, and the outer map function performs the rounding operation. The outputs are identical in both of the above approaches. However, you should ensure that the code is readable and maintainable when nesting functions as shown above.
How to Use map() Function with Lambda Functions
In the previous sections, you learned how to use the Python map() function with built-in and user-defined functions. You’ll now learn how to use the map() function with lambda functions, which are anonymous in Python. Sometimes, you’ll have a function whose body contains only one line of code, and you may need to use the function only once and not reference it elsewhere in the program. You can define such functions as lambda function in Python. #1. Consider the following list strings. Suppose you want to get a list strings_rev – containing a reversed copy of each of the strings. We can reverse a Python string using string slicing. You can use this lambda function: lambda x:x[::-1]Inside the map function, as shown below. – Without the start and stop values, the slice starts at the beginning of the string and extends up to the end of the string.– Negative values of step gives slices starting from the end of the string.– Therefore, str[::-1] returns a reversed copy of str. As with other examples, we cast the map object into a list. In the output, we see that each of the strings in the list strings has been reversed. #2. In the previous section, we computed the square root of every number in the numbers list and then rounded each square root value to two decimal places. We used the function round_2() to do this. Let’s rewrite the round_2() function as a lambda function and use it with the map() function described below. As seen below, the output is identical to what we obtained from using the round_2() function.
How to Use map() Function with Multiple Iterables
In the examples we have seen, we applied a function on all items of exactly one iterable. Sometimes, we may have functions that take in two or more arguments. In this case, each argument is stored in a list or any similar collection. We can also use the Python map() function with multiple lists. #1. Consider the following function area() that accepts the length and breadth as inputs and returns the area, length*breadth. The length and breadth of different rectangles are stored in two separate lists, lengths and breadths, respectively. We can use the map() function to apply the area function on the above lists by passing in both the lengths and breadths lists. Because the function area accepts two arguments, the length and breadth values are used from the lists lengths breadths, respectively. #2. The Python math module has the log function that helps us compute the logarithm of a number to any base. In this example:
The list x corresponds to the values for which you’d like to compute the logarithm.The base list contains all base values to be used in the logarithm computation.
We can use the Python map() function with math.log, the lists, x and base to get the new list log_x, as follows. Here’s the output.
Conclusion
Here’s a summary of what you’ve learned in this tutorial:
The Python map() function takes in at least two arguments: a function and an iterable, with the syntax map(function, iterable(s)).The function can be any valid Python callable.When the function takes in k arguments, use the map() function with the function and each of the k arguments in an iterable.
Next, learn to work with sets in Python.