Python list filtering using the built-in `filter' function and lambda
Often we need to filter some items in the list according to some criterion. Python provides several ways to do this. And some may think of list comprehension with an `if` condition first. However, there is a built-in `filter' function that works well in many cases.
The built-in `filter' function takes as arguments the actual function which filters the list, and the reference to the list to filter. Only those items will pass filtering on which the filtering function returns True (or some other value that is interpreted in Python as True). If the filtering rule is something simple, like evenness in this case, we can not bother to define the function separately, but instead include that function as a one-liner, using lambda syntax.
1 2 3 4 5 6 | nlist: list evens: list nlist = [1, 2, 33, 14, 0, 2, 6, 8, 4, 2, 3] evens = list(filter(lambda x: x % 2 == 0, nlist)) print(evens) |
But wait... x? What is going to be x there? The decision of what will be passed as the argument(s) to a lambda function depends on the context. In this case, we are applying this function to an iterable data structure (list), and x will point to each list element in turn.
It is important to remember, however, that the `filter' function does not return a filtered list or tuple, but rather a pointer to an iterator (a kind of function that produces a value on each call, until it is exhausted). So if you need a list output, you'll have to explicitly "consume" the iterator with a list function, as shown below.
...