Menu Close

Python map() Function

In this Python guide, we are going through the Python map() function to execute a specific function for each item for an iterable.
map function in Python is the most important function when you want to execute a function for each item of an iterable.


In the previous Python built-in functions tutorials, we have seen various functions along with examples.

What is Python map() function?

The python map function is a built-in function. map() is used to apply a specific function on each item of an iterable (list, tuple, etc) and return a list of results.

Syntax

The syntax of map function in python is:-

map(function, iterable)

Parameter

map function in Python accepts two parameters.

  • function:- Required, the function executed for each item.
  • iterable:- Required. A sequence, collection, or an iterator object.

Python map() function examples

We will understand map function along with some examples.

Example 1:

Convert string number to int list.

a = '1234567'
x = map(int, a)
print(list(x))

Output will be:- [1, 2, 3, 4, 5, 6, 7]

Example 2:

Convert list of string into list of integer.

abc = ['1', '2', '3', '4', '5', '6', '7']
print(list(map(int, abc)))

Output will be:- [1, 2, 3, 4, 5, 6, 7]

Example 3:

Convert tuple of integers into set of string using map function.

x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y = map(str, x)
print(set(y))

Output

{'7', '4', '2', '1', '5', '8', '6', '9', '3', '10'}

map() function with custom function

You can use python map function with custom function Python function as well.

Example 1:

We have function myfunction that find the length of the each item of the list.

def myfunction(name):
    return len(name)


mylist = ['Python', 'Programming', 'Java', 'JavaScript', 'Programmer']
x = map(myfunction, mylist)
print(list(x))

Output will be:- [6, 11, 4, 10, 10]

Example 2:

Calculate square of each item of a list using custom function and map() function.

def Calculate(n):
    return n * n

numberlist = [2, 4, 5, 6, 7, 8]
x = map(Calculate, numberlist)
print(list(x))

Output will be:- [4, 16, 25, 36, 49, 64]

Conclusion

In this tutorial, you have learned all about the Python map function to execute a specific function for each item of an iterable.
This is the best built-in function when you want to perform a specific operation on each item of iterable.

If you like this article, please share and keep visiting for further python built-in functions.

Python built-in functions

For more information:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts

Leave a Reply