Home > Notes > python

Python Filter

python

Python Variable
Python Conditional statement
Python loops
Python List
Python Tuple
Python String
Python Set
Python Dictionary
Python Functions
Python Exceptions
Python File Operation
Python Map
Python Lambda
Python Filter
Python OOPS

Python Filter

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)

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

# 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)) 

Python Filter Example1

The filter function in Python is a built-in function used to construct an iterator from elements of an iterable (like lists, tuples, or strings) for which a function returns true. It is commonly used for filtering elements based on some criteria.

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)

Python Filter Example2

The filter function in Python is a built-in function used to construct an iterator from elements of an iterable (like lists, tuples, or strings) for which a function returns true. It is commonly used for filtering elements based on some criteria.

# 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))