⊗pyPmFnFi 18 of 128 menu

The filter function for filtering objects in Python

Now let's study the filter function. It allows you to filter elements of lists and other iterables based on some condition. Its first parameter is a function that specifies the condition to check. The second parameter specifies the list whose elements will be filtered. If the function returns True, the element remains in the new list. If False is returned, the element will not be included in the list.

Let's say we have a list:

lst = [1, 2, 3, 4, 5, 6]

Let's leave only even numbers in it. To do this, we'll use the lambda function to write down that the number passed to its parameter is divisible by: 2 without a remainder:

res = filter(lambda num: num % 2 == 0, lst) print(list(res))

After executing the code, a new list will be returned:

[2, 4, 6]

Given a list of numbers:

lst = [1, 2, 3, 4, 5]

Write only the odd numbers from this list into a new list.

Given a list of lines:

lst = ['abcd', 'ab', 'c', 'de', 'bc']

Write to the new list only the strings whose length is 2.

enru