Docy

Python Filter

Estimated reading: 1 minute 1146 views

Filter Overview

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

				
					ages = [5, 12, 17, 28, 24, 32]

def myFunc(x):
  if x > 18:
    return False
  else:
    return True


adults = filter(myFunc, ages) 
#print(adults)
print(list(adults))
#for x in adults:
#  print(x)
				
			
				
					# a list contains both even and odd numbers.  
seq = [0, 1, 2, 3, 5, 8, 13] 
  
# result contains odd numbers of the list 
#result = filter(lambda x: x % 2, seq) 
#print(list(result)) 
  
# result contains even numbers of the list 
result = filter(lambda x: x % 2 == 0, seq) 
print(list(result)) 
				
			

Leave a Comment

Share this Doc
CONTENTS