PYTHON: The Map() Function

Code-Parser
427 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

PYTHON: The Map() Function

In Python, there is a built-in function in the standard library called map().

The map() function is useful for iterating through a list/array.

Let's explore this cool function:

Exploring the Map() Function

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

Here's an example:

Let's dive deeper:

First we create a variable string with a string of numbers (1-4) separated by spaces.

Let's look at the part to the right of the equals symbol: map(int, string.split(" ")).

  1. We have split the string into an array of string values by splitting at every occurence of a space.
  2. We then iterate through each value in the array and convert each value to an integer.
  3. Then we call the 4 values a, b, c and d respectively.

This is handy, right?

You can also do this with str, float, etc...

Program: The Map() Function in Action!

Now that we've explored it, let's implement it in a program.

The result should be 120.

Try it for yourself!

Give it a go and explore the map() function.

Conclusion

There you go. A begginer tutorial to the map() function.

If you're interested in learning more about this function, here are some links that might help you:

https://www.w3schools.com/python/ref_func_map.asp

https://www.geeksforgeeks.org/python-map-function/?ref=gcse

https://docs.python.org/3/library/functions.html#map

https://realpython.com/python-map-function/

Happy Coding, @Code-Parser

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content