×


Python's map() Function - An Overview ?



Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable. map() is one of the tools that support a functional programming style in Python.

Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Python's map() queries.

In this context, we shall look into how to use the map() function in Python.


What is map() function in Python ?

The map() function executes a specified function for each item in an iterable file. Item in function as a parameter.


What is the syntax for map() function ?

Its syntax is provided below:

map (function, iterables)

Here, the Parameter Values are explained below:

  • function: The function executes for each element in the iterable.
  • iterables: a list, tuple, dictionary… want to browse.


map() function examples

Let's take a look at a few examples like:

def func(n):
return len(n)
x = map(func, ('cat', 'dog', 'tiger'))
print(x)
print(list(x))

When you run this program, you will see an output such as this:

<map object at 0x00000000020E7940>
[3, 3, 5]

Also, we can look at some more examples.

1. Double the variable value n:

def calc(n):
#Double n
return n + n
numbers = (2, 4, 6, 8)
result = map(calc, numbers)
#Convert map object to list
print(list(result))

Its output will look like this:

[4, 8, 12, 16]


2. Using lambda function with map():

numbers = (2, 4, 6, 8)
result = map(lambda n: n+n, numbers)
print(list(result))

The resulting output will look like:

[4, 8, 12, 16]


3. Passing multiple iterator parameters to map() using lambda:

num1 = [2, 3, 4]
num2 = [4, 5, 6]
result = map(lambda x, y: x + y, num1, num2)
print(list(result))

Its Output will give:

[6, 8, 10]


[Need assistance in fixing Python issues? We can help you. ]


Conclusion

This article covers how to use the map() function in Python. In fact, map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.). Sometimes you might face situations in which you need to perform the same operation on all the items of an input iterable to build a new iterable. The quickest and most common approach to this problem is to use a Python for loop. However, you can also tackle this problem without an explicit loop by using map().


More Linux Tutorials

We create Linux HowTos and Tutorials for Sys Admins. Visit us on IbmiMedia.com

Also for Tech related tips, Visit forum.outsourcepath.com or General Technical tips on www.outsourcepath.com