0

filter() definition simplified? (PY)

I just don't get it, or the syntax either.

21st Sep 2024, 4:15 AM
Xmosity
4 Answers
+ 5
The Python filter() function is like a shortcut to writing a for loop. It is not a replacement for all for loops, but rather a specific kind with an if statement that chooses which items belong or don't belong in a group of items. You supply the items to filter in its second argument. Filter loops over those items and tests each one according to the conditional function that you supply in the first argument. Like a for loop, filter passes each item (one at a time) as an argument into the True/False function, then checks the return value. If your function returns false, then filter ignores that item and skips to the next item. If your function returns true, then filter includes that item in its output. filter(<True/False function>, <iterable items>)
21st Sep 2024, 5:25 AM
Brian
Brian - avatar
+ 1
Thanks
21st Sep 2024, 5:27 AM
Xmosity
+ 1
Bob_Li , this is what the *python docs* say about `filter` and `generator`: filter(function, iterable) > Construct an iterator from those elements of iterable for which function is true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed. > Note that filter(function, iterable) is equivalent to the generator expression: (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None. > See itertools.filterfalse() for the complementary function that returns elements of iterable for which function is false.
21st Sep 2024, 3:07 PM
Lothar
Lothar - avatar
0
nums = (1,2,3,4,5,6) res = filter(lambda x: x%2==0, nums) print(res) print(*res) filter is a generator function. you can convert it to a list, or iterate the result from it
21st Sep 2024, 11:55 AM
Bob_Li
Bob_Li - avatar