4

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.

1
  • 2
    Not sure why this was down voted a couple of times, seems like a good question, albeit basic. Beginner questions are welcome here! Commented Jul 23, 2013 at 11:08

2 Answers 2

3

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

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

Or as a list comprehension:

[i for i in lst if i == y]
Sign up to request clarification or add additional context in comments.

1 Comment

There was a time restriction on when I could accept it so I was just waiting.
3

Adding to Haidro’s answer, in Python 3 filter is a generator, so you could reimplement it like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.