Sunday 18 January 2015

Python map, filter, lambda explained with example

map(function, sequence[, sequence, ...]) -> list

map(function, iterable, ...) is a python builtin function.
  • It returns a list of results applying the function to the items of the argument sequence(iterable) or sequences.
  • If more than one iterable arguments are passed, the function must take that many arguments. The function is called with an argument list consisting of the corresponding item of each sequence.
  • If one iterable is shorter than another it is assumed to be extended with None items.
We can examine these rule with some codes.

def square(a):
    return a ** 2

Here  square is a function that makes a number square. We want the square of number 0 to 5. Using map(),

>>> map(square, range(6))
[0, 1, 4, 9, 16, 25]

So map() takes a function square and a list as arguments and returns a list of square(item).  Here item is elements in the list range(6).
If we pass two iterable in map(), the function must take two arguments.

def my_pow(a, n):
    return a ** n


Now my_pow function takes two arguments a, n and returns an.

>>> map(my_pow, [2, 3], [3, 2])
[8, 9]

But what if the two iterables are not of same length? In this particular case it will  generate a TypeError.



filter(function or None, sequence) -> list, tuple, or string

filter(function, iterable) is a python builtin function.
  • It returns those items of sequence for which function(item) is True.
  • If function is None, return the items that are True.
  • If sequence is a tuple or string, return the same type, else return a list.
We want to filter out the even integer from a list and we have written a function for this.

def is_odd(n):
    if n % 2 == 1:
        return True    
    return False

is_odd  function takes an integer and returns True if it's odd number otherwise returns False.

>>> filter(is_odd, range(10))
[1, 3, 5, 7, 9]

What happens here is, filter() applies the is_odd function on each item of the list range(10) and returns a list of those items for which is_odd returned True. It filters out the other items.


>>> filter(None, k = [True, False, True, False])
[True, True]

If the function is None it return the items that are True


lmabda function:

Now, fun begins with lambda functions. in Python,
  • lambda operator is a way to create small anonymous function. An anonymous function is a function without a name.
  • lambda function can be used wherever a normal function is used but it's restricted to a single expression.
  • function require multiple expression can not be expressed using lambda.
lambda functions are written as:
lambda arguments: expression (operation to perform on arguments)
lambda function returns the result of the operation.

What we have done in map() and filter() examples is, separately wrote a function and pass those in map(), filter()

We can do the same using lambda function.

>>>  map(lambda n: n**2, range(6))
[0, 1, 4, 9, 16, 25]

what happens here is same in the map() example but in this case a lambda function is used.

lambda n: n**2

On the left of : are the arguments. Here n is the argument and on right side is the expression that will be applied to the argument. The return value is the result.

>>> map(lambda a, n: a**n, [2, 3], [3, 2]) 
[8, 9]

This is equivalent to the my_pow() example.

Suppose we want to get all the digits from a string. According to our filter() and lambda knowledge,

>>> filter(lambda s: s.isdigit(), "adf9df215")
'9215'

We can write a little complex expression in lambda.

>>> filter(lambda s: False if s.isspace() else True, "This is SPARTAAAAAAA")
'ThisisSPARTAAAAAAA'

This filters out all the space from the string. Hope king  Leonidas don't mind.

No comments :

Post a Comment