-2

I got the following code:

f = lambda y, z: filter(y, z)
g = lambda x: [x for x in range(int(x**0.5))]

r = f(g, g(11))

I was wondering how r ended up being [1,2].

I understand why g(11) is [0,1,2] but I didn't quite catch how the filter function works here.

0

1 Answer 1

2

After doing all necessary replacements, the functions above can be simplified to

filter(lambda x: [x for x in range(int(x**0.5))], [0, 1, 2])

Now for x=0, the list will be empty (since [x for x in range(int(0**0.5))] is an empty list due to range(0)), and hence will evaluate to False, and for x=1,2 it will evaluate to True since it will be non-empty.

filter constructors the iterator based on the elements for which the function returns True, hence 0 is filtered out of the list and we get [1,2] as the output of the filter function

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.