Writing a filter () function using / while loops

I am trying to understand how the filter() function works and would like to know how I could write:

 test = filter(lambda x: x == y, lst) 

using for or while loops.

+4
source share
2 answers

filter() pretty much creates a new list with a for loop and a conditional. In your example, it is identical:

 L = [] for i in lst: if i == y: L.append(i) 

Or as a list comprehension:

 [i for i in lst if i == y] 
+3
source

Adding Haidros to the answer, in Python 3 the filter is a generator, so you can implement it like this:

 def filter (test, lst): for x in lst: if test(x): yield x 
+3
source

Source: https://habr.com/ru/post/1492926/


All Articles