evaluates to the list 2, 4, …, 10 by applying the predicate even to every element of the list of integers 1, 2, …, 10 in that order and creating a new list of those elements for which the predicate returns the Boolean value true, thereby giving a list containing only the even members of that list. Conversely, the code example
filter(not.even)[1..10]
evaluates to the list 1, 3, …, 9 by collecting those elements of the list of integers 1, 2, …, 10 for which the predicate even returns the Boolean value false (with . being the function composition operator).
Visual example
Below, you can see a view of each step of the filter process for a list of integers X = [0, 5, 8, 3, 2, 1] according to the function :
This function express that if is even the return value is , otherwise it's . This is the predicate.
View of processing steps when applying filter function on a list
Here, [] denotes the empty list, ++ the list concatenation operation, and [x | p x] denotes a list conditionally holding a value, x, if the condition p x holds (evaluates to True).
The function remove-if-not has been deprecated[5] in favor of the equivalent remove-if where the predicate is complemented.[9] Thus the filter (remove-if-not#'oddp'(0123)) should be written (remove-if(complement#'oddp)'(0123)) or more simply: (remove-if#'evenp'(0123)) where evenp returns the inverted value of oddp.[10]
Or, via list comprehension: [x for x in list if pred(x)]. In Python 3, filter was changed to return an iterator rather than a list.[13] The complementary functionality, returning an iterator over elements for which the predicate is false, is also available in the standard library as filterfalse in the itertools module.
iterator is an Iterator and the filter method returns a new iterator; pred is a function (specifically FnMut) that receives the iterator's item and returns a bool
In block the context item . holds the current value
Variants
Filter creates its result without modifying the original list. Many programming languages also provide variants that destructively modify the list argument instead for faster performance. Other variants of filter (e.g., Haskell dropWhile[14] and partition[15]) are also common. A common memory optimization for purely functional programming languages is to have the input list and filtered result share the longest common tail (tail-sharing).