4 Sept 2013

Tweaking filter() of python

Following is basic list comprehension example which filter out the even numbers from a list.
>> [ x for x in [1,2,3,4] if  if n%2==0]
[2, 4]

Same can be achieved from filter(func, sequence). And for that we have to write the filter logic in a function, say poi().

>> def pp(n):
...     if n%2==0:
...             return True
...     else:
...             return False
...

>> filter(pp, [1,2,3,4])
[2, 4]

Upto here it seems that the filter(func, seq) takes a function as a first argument and sequence type (list, tuple , string, unicode or xrange() ) as a second argument. And for each element of sequence type it runs the function and returns elements of type seq.
The elements of returned list are initialized from the function, for which function returns True.

To see how filter() behaves ,return type of poi() has been played with.
Tweak 1: what if return type is False or None ?
def poi(x):
    return X    //X =False or None
>> filter(poi, [1,2,3,4])
[]

Tweak 2: what if i return type is string ?
Lets say for 2 in list , i want to return "two". 
def poi(x):
    if x==2:
        return "two"
>> filter(poi, [1,2,3,4])
[1, 2, 3]

Tweak 3: what if i return type is int ?
Lets say for 2 in list , i want to return 4.
def poi(x):
    if x==2:
        return x*x
>> filter(poi, [1,2,3,4])
[1, 2, 3]


What i learned :

1. filter(func, seq) will create a list of elements for which the function , poi() , returns True.
2. if poi() returns False or None for an element then resultant list will be an empty list.
3. if poi() returns other than boolean,  then it will return given list of filter.

What i understood:

say i have a sequence S having n elements and i want to filter the elements on some boolean condition, then filter() can rescue me.  Note that resultant sequence type will have all or some elements of given sequence for which boolean condition is True.


No comments:

Post a Comment