How this code execution works ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How this code execution works ?

l = [1,2,False,1,1,{},'',0,44] f = filter(None, l) for i in f: print(i) In the above code, I have 2 queries. 1. The filter function accepts a function and a sequence as arguments. But here, None is used in place of a function. So how is it possible to call None as a function ? 2. In case of filter function, we return either True or False, so the filter function should print True or false right , how the values are getting printed finally. ( Quite confused how the filter function works)

28th Aug 2022, 4:52 AM
Levi
Levi - avatar
3 Answers
+ 1
I re-wrote the code a little so you can see what is going on: https://code.sololearn.com/cAcLxu1a450G/?ref=app In summary, filter(None, l) filters out all elements that have a truth value of False.
29th Aug 2022, 4:16 PM
Lisa
Lisa - avatar
+ 1
Quoting from the docs: If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed. https://docs.python.org/3/library/functions.html#filter
29th Aug 2022, 4:59 PM
Lisa
Lisa - avatar
0
Lisa I can able to get what the filter does in this case , but my question is how it's filtering out ? Because none is not callable right ?
29th Aug 2022, 4:55 PM
Levi
Levi - avatar