Using the map function

Map is a built-in Python function. It takes a function and an iterable for an argument:

map(aFunction, iterable)

The function is applied on all the elements of the iterable and results are returned as a list. As a function is passed to map, lambda is most commonly used along with map.

Getting ready

Let's look at a very simple example using the map function.

How to do it…

Let's see an example on how to use a map function:

#First let us declare a list.
a =[10,20,30]
# Let us now call the map function in our Print statement.
print map(lambda x:x**2,a)   

How it works…

This is very similar to the code in the previous recipe. A map functions takes two parameters. The first one is a function and second one is a sequence. In our example code, we used an anonymous function:

lambda x:x**2

This function squares the given input. We also passed a list to map.

Map applies a function that squares all the elements in the given list and returns the result as a list.

The output is as follows:

[100,400,900]

There's more…

Similarly, any other function can be applied to a list:

print map(lambda x:x**3,a)

Using map, we can replace the code snippet in the previous recipe with a single line:

print sum(map(lambda x:x**2,a))
print sum(map(lambda x:x**3,a))

Map expects an N-argument function if we have N-sequences. Let's see an example to understand this:

a =[10,20,30]
b = [1,2,3]

print map(pow,a,b) 

We passed two sequences a and b to our map function. Notice that the function passed is the power function. It takes two arguments. Let's see the result of the preceding code snippet:

[10, 400, 27000]
>>>

As you can see, the elements of list a is raised to the power of value in the same position in list b. A point to note is that both the lists should be of the same size; if not, Python will fill the smaller list with None. Though our examples are operating on a list, any iterable can be passed to a map function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset