Python                                                          Home : www.sharetechnote.com

 

 

 

 

Python - Filter

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

  • Applying a filter with normal function with one argument  - Example 1
  • Applying a filter with lambda function with one argument - Example 2
  • Printing out all the items in a Filtered Object - Example 3
  • Printing out all the items in a Filtered Object - Example 4
  • Indexing items in a Filtered Object - Example 5

 

 

Examples :

 

< Example 1 >

 

def getEven(x):

    if (x % 2) == 0 :

        return True

    else :

        return False

 

numList = [0,1,2,3,4,5,6,7,8,9,10]

 

evenList = filter(getEven,numList)

print(evenList)

print(list(evenList))

 

Result :----------------------------------

 

<filter object at 0x02FF18D0>

[0, 2, 4, 6, 8, 10]

 

 

< Example 2 >

 

numList = [0,1,2,3,4,5,6,7,8,9,10]

 

evenList = filter(lambda x :(x % 2) == 0,numList)

print(evenList)

print(list(evenList))

 

Result :----------------------------------

 

<filter object at 0x03121930>

[0, 2, 4, 6, 8, 10]

 

 

< Example 3 >

 

numList = [0,1,2,3,4,5,6,7,8,9,10]

 

evenList = filter(lambda x :(x % 2) == 0,numList)

 

for index, item in enumerate(evenList):

    print(index,',',item)

 

Result :----------------------------------

 

0 , 0

1 , 2

2 , 4

3 , 6

4 , 8

5 , 10

 

 

< Example 4 >

 

numList = [0,1,2,3,4,5,6,7,8,9,10]

 

evenList = filter(lambda x :(x % 2) == 0,numList)

 

for item in enumerate(evenList):

    print(item)

 

 

Result :----------------------------------

 

(0, 0)

(1, 2)

(2, 4)

(3, 6)

(4, 8)

(5, 10)

 

 

< Example 5 >

 

numList = [0,1,2,3,4,5,6,7,8,9,10]

 

evenList = filter(lambda x :(x % 2) == 0,numList)

 

evenList = list(evenList);

 

print(evenList)

print(evenList[0])

print(evenList[1:3])

    

 

Result :----------------------------------

[0, 2, 4, 6, 8, 10]

0

[2, 4]

 

 

 

< Example xx >