Computer >> Computer tutorials >  >> Programming >> Python

Lambda and filter Examples in Python


In this tutorial, we are going to see a different example of the lambda and filter functions in Python. Let's start the tutorial by knowing about the lambda and filter expression and function respectively.

lambda Expression

lambda expression is used to write simple functions simply. Suppose if we want to find about even numbers then, writing a lambda expression will save time for us.

If you are not familiar with the lambda expression go to the tutorial section of tutorialspoint to learn about it in more detail.

filter(func, iter) function

filter(func, iter) takes two arguments one is function and another one is iter variable, and it returns filter object which we can convert into an iterator. The resultant iterator will contain all the elements which are returned by the func by performing some operation that has written inside the function.

If you are not familiar with the filter function go to the tutorial section of tutorialspoint to learn about it in more detail.

So, we have noticed that we can use lambda expressions inside the filter(func, iter) function. Let's see one example which filters out the even numbers from a list.

See the expected input and output.

Input:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output:
[2, 4, 6, 8, 10]

Let's follow the below steps to achieve our desired output.

Algorithm

1. Initialise the list of numbers.
2. Write a lambda expression which returns even numbers and pass it to filter function along with the iter.
3. Convert the filter object into an iter.
4. Print the result.

Let's see the code.

Example

## initializing the list
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## writing lambda expression inside the filter function
## every element will be passed to lambda expression and it will return true if it
satisfies the condition which we have written
## filter function function will yield all those returned values and it stores them
in filter object
## when we convert filter object to iter then, it will values which are true
result = filter(lambda x: x % 2 == 0, nums)
## converting and printing the result
print(list(result))

Output

If you run the above program, you will get the following output.

[2, 4, 6, 8, 10]

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.