Functions map, zip and lambda in Python

Hello everybody,

today I want to describe three elements of Python: map, zip, lambda and *.

Zip and *

The first step that I want to describe is zip and * usage. Take a look at the following code:

a = [5, 6]
b = [7, 8]
c = zip(a,b)

How do you think, what will be output, if I'll tell you that zip function zips arrays? If your guess is (5, 6) (7, 8) then unfortunately you are wrong. Output will be the following:

(5, 7) (6, 8). I suppose that zip name was chosen because as usually zippers on clothes as usually vertical. Zip functions "zips" elements by columns, like presented on the picture:

Now one more question, what is purpose of * ? It tells to Python interpreter to treat each element and not just reference to memory.

Function map

Next function that I'd like to present goes map. That function is needed for cases if you need to apply the same function for element of array and get another array after that function. For such purposes exists function map. Take a look at the code:

def squareFun(x):
    return x*x
numbers = [5, 6, 8]
for number in numbers:
    print( squareFun(number))

as result you'll get squares of numbers. In Python you can do it in another way with usage of list comprehensions:

def squareFun(x):
    return x*x
numbers = [5, 6, 8]
print( [squareFun(numfor num in numbers])

which is fine and good way to go. 

And now take a look how to achieve the same with map:

def squareFun(x):
    return x*x
numbers = [5, 6, 8]
print(* map(squareFun, numbers))

I can't say that in this particular example it's easier or nicer, but you've got an idea.

If you incline better to see standard description, then take a look how map is declared. For example like this:

r = map(func, seq)

As you can see map takes two parameters: some function func and some sequence of elements seq. map() will apply function func to each element of the sequence seq and will return sequence on which function was applied. 

Next try to compare it with 

map + lambda

Take a look at the following code sample:

numbers = [5, 6, 8]
print( *map(lambda xx*x, numbers))

take note that we don't have function squareFun described. You may wonder, why somebody can have desire to use lambda isntead of full grown function? The main reason is that lambda function can be written in one line, while function with formatting will require 4 lines with formatting. It's like ++ operator in C#, Java or C++. It's easier to write i++ then i = i + 1. One more point to keep in mind is that lamda expressions can be used when it is needed to pass in other function some kind of calculations.

No Comments

Add a Comment