Monday 20 September 2021

Python: filter function

‘filter’ function takes a function and iterable as argument and return an iterable of values for which the function evaluates to True.

 

Signature

filter(function, iterable)

 

Example: Get even numbers from the list of numbers

Step 1: Define a function that takes a number as input and return True if it is even, else False.

def is_even(number):
    return (number % 2 ) == 0

 

Step 2: Use filter() function to get the even numbers from the iterable of numbers.

numbers = range(0, 10)
evenNumbers = list(filter(is_even, numbers))


Find the below working application.

 

filter_1.py

numbers = range(1, 10)

def is_even(number):
    return (number % 2 ) == 0

def is_odd(number):
    return (number % 2) != 0

evenNumbers = list(filter(is_even, numbers))
oddNumbers = list(filter(is_odd, numbers))

print('numbers -> ', list(numbers))
print('evenNumbers -> ', evenNumbers)
print('oddNumbers -> ', oddNumbers)


Output

numbers ->  [1, 2, 3, 4, 5, 6, 7, 8, 9]
evenNumbers ->  [2, 4, 6, 8]
oddNumbers ->  [1, 3, 5, 7, 9]


Can I use a lambda inside filter?

Yes, you can use.

 

filter_lambda.py

numbers = range(1, 10)

evenNumbers = list(filter(lambda x: (x%2 == 0), numbers))
oddNumbers = list(filter(lambda x: (x%2 != 0), numbers))

print('numbers -> ', list(numbers))
print('evenNumbers -> ', evenNumbers)
print('oddNumbers -> ', oddNumbers)


Output

numbers ->  [1, 2, 3, 4, 5, 6, 7, 8, 9]
evenNumbers ->  [2, 4, 6, 8]
oddNumbers ->  [1, 3, 5, 7, 9]



Previous                                                    Next                                                    Home

No comments:

Post a Comment