Question:
Write a program which can filter even numbers in a list by using filter function. The list is: [11,12,13,14,15,16,17,18,19,20]. Use filter() to filter some elements in a list. Use lambda to define anonymous functions.
Program:
1 2 3 |
li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = filter(lambda x: x%2==0, li) print evenNumbers |
Explanation:
The function filter(function, list) offers an elegant way to filter out all the elements of a list for which the function function returns True.
The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True, the element of the list be included in the result list.
Output:
1 |
[12, 14, 16, 18, 20] |
Leave a Reply