filter() function takes a function and an iterable as arguments and it returns the items for which the function returns True.
For example,
def is_odd(n): if n % 2 == 0: return False else: return True numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers = list(filter(is_odd, numbers)) print (odd_numbers)
Here, the function is_odd(n) returns True if n is odd. Hence, the function filter(is_odd, numbers) will return those numbers from the list “numbers” for which is_odd returns True. In other words, the new list odd_numbers will now contain all odd numbers from the list “numbers”. The above program will print the following output:
[1, 3, 5, 7, 9]
Now, we can solve the problem very easily using a lambda function. The filter() function can take a lambda function as an argument and return the list of odd numbers.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers2 = list(filter(lambda x: x % 2 != 0, numbers)) print(odd_numbers2)
Here, the lambda function takes x as an argument and evaluates True if x is odd. As a result, the filter() function will filter out all the odd numbers and the list odd_numebers2 will contain the following numbers:
[1, 3, 5, 7, 9]
Hence, we can use a lambda function to reduce the number of lines in a piece of code. Also, we can define a lambda function within the code and call it immediately after the definition. Lambda functions can also be used with other built-in functions like filter(), reduce(), etc., and reduce the number of lines of code significantly.






0 Comments