You are currently viewing How to Use map() Function in Python With Examples

How to Use map() Function in Python With Examples

What would you do if you wanted to apply a function to each item in an iterable? Your first step would be to use that function by iterating over each item with the for loop.

Python has a function called map() that can help you reduce performing iteration stuff and avoid writing extra code.

Python’s map() Function

The map() function in Python is a built-in function that allows you to apply a specific function to each item in an iterable without using a for loop.

Syntax

map(function, iterable)

  • function: map() applies this function to each item in the iterable.
  • iterable: list, tuple, string, or iterator object.

The map() function returns an iterator object containing the result, which can be iterated over to generate values on the fly.

Let’s take a closer look at the map() function with an example.

Example

Consider the following example: a function called add_two() adds 2 to the argument a. The map() function applies the function (add_two()) to the iterable stored in the variable my_iterable.

When you run the above code, you’ll get a list in which each element from the original list my_iterable has been incremented by 2, as specified by the add_two function.

You may be wondering how the function is applied to each item in the iterable without the use of an explicit for loop. How does the map() function do it?

How map() Function Works?

You now know that the map() function applies a function to each item in the iterable, but how exactly does it do so?

Let me explain with an example. How would you apply a function to the items in a list without using the map() function? You’ll use the for loop to iterate through each item in the list and then apply the function.

As you can see in the above code, a for loop is used to iterate through each item in the my_iterable variable, and within the for loop, the add_two function is applied to each item, with the result appended to a list final_list and printed.

When you run the above code, you will get a similar result as in the first example.

That is exactly how the map() function would have worked in the background for simple operations like the one above.

You can imitate the map() function in just one line of code for the above example.

Using the list comprehension in the above code eliminated the need to write the additional lines of code.

Processing Multiple Inputs Using map()

Consider the following scenario: you need to take multiple user inputs and process them using a function. How would you efficiently process the inputs? You can use the map() function to accomplish your goal.

The code above accepts multiple user inputs, separated by a space (input().split()), and the int function will be applied to each input using map() before being converted into a list using the list function.

The next block applies the to_celcius function to the iterable f_values and prints the results.

Using map() with Multiple Iterables

So far, you’ve only used the map() function with a single iterable, but the map() function can accept multiple iterables.

Consider the following example, in which multiple iterables are processed using the map() function.

In the above code, both iterables (first and second) and the add function is passed to the map() function.

The map() function iterates each element from both iterable and applies the add function. The add() function takes two arguments, x and y, and returns the sum of their values. In the first iteration, x will be 2 and y will be 1 and the output will be 3 and this will continue till the end of the shortest iterable.

Using map() with lambda Function

The lambda expression creates an anonymous function in a single line of code. Using the map() function and a lambda expression, you can achieve the desired result in a few lines of code.

The lambda expression in the code above is the same as the previous section’s add function. Using the lambda expression eliminates the need to explicitly declare a named function, saving a few lines of code.

The above code will produce the following output.

Manipulating Iterables of String

Not just integers or floats, the map() function can be used to transform iterables containing various types of elements, including strings.

The map() function is used in the above code to apply the str.upper and str.capitalize functions to the words variable (a list of strings). When you run it, you will notice that the strings are transformed.

You can also perform various other operations by declaring a function. For instance, you can declare a function to reverse the strings or slice out some parts from the string.

Output

Conclusion

In simple terms, the map() function maps a function to each item in an iterable and returns an iterator object. This iterator can be looped over or converted into a data type, such as a list.

In this article, you’ve learned:

  • What is the map() function and how to use it?
  • How map() works and imitating the map() function using for loop and list comprehension.
  • Processing multiple user inputs using map().
  • Processing multiple iterable using map().
  • Using lambda expression with map() to eliminate creating a named function.
  • Manipulating iterable containing string items.

πŸ†Other articles you might be interested in if you liked this one

βœ…Serialize and deserialize Python objects using the pickle module.

βœ…How to use pytest to test your Python code?

βœ…Create a WebSocket server and client in Python.

βœ…Create multi-threaded Python programs using a threading module.

βœ…Create and integrate MySQL database with Flask app using Python.

βœ…Upload and display images on the frontend using Flask.


That’s all for now

Keep Coding✌✌