An example of filter using python3 code to iterate elements

  • 2021-08-12 03:08:00
  • OfStack

We usually say that we use functions to filter lists. How many small partners can understand the principle of filtering?

Today, this site brings you a new friend filter function, compared to the previous functions that can achieve screening function is complex, this is also a test for 1 difficult function learning. We will focus on the filter function after the filtering of the return value, for the return value of the iterative analysis of a number of principles.

filter is used to filter the elements in the iterable object, and if it meets the conditions, it returns the corresponding element sequence (type filter). filter accepts two parameters, one is the function used to filter the elements, and the return value is True or Flase, and the other is the iterable object.

Usage of filter


evens = filter(is_odd, range(-5, 10))
print(list(evens))

Example results:


[2, 4, 6, 8]

The return value of the filter function is an iterable object, which is a key point, which is why I say the filter function is a high-level syntax.

Why not return the list? If a list is returned, during the execution of filter function, every data in the list must be modularized by 2, which wastes space. Therefore, filter adopts iterator technology in implementation, and delays the calculation until the result returned by filter function is iterated.


Related articles: