Can Someone Explain this:- | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can Someone Explain this:-

a=[0,5,0,1,'Python'] print (list(filter(bool,a)))

14th Aug 2021, 4:34 AM
Amol Bhandekar
Amol Bhandekar - avatar
3 Answers
+ 3
The list() function creates a list of the values ​​of the variable "a" filtered by the filter() function, which are equal in boolean type "True". All numbers except "0" and all string characters are "True" by boolean type.
14th Aug 2021, 5:07 AM
Solo
Solo - avatar
+ 4
Amol Bhandekar I guess that you're finding trouble with understanding what the filter() method does. The filter() method takes in a function as it's first argument and an iterable (something that can be used with a for loop, which can be iterated upon) as its second argument. It filters all the values inside the iterable given as the second argument according to the boolean return value of the function, provided as the first argument and returns another iterable based on that. Here, 'filter(bool, a)' filters all the values in the list 'a' according to its boolean value. The list() method then converts this iterable into a list. Your code outputs [5, 1, "Python"] as 0 has the boolean value 'False' and hence, it's rejected by the filter method. Note that 'bool' acts as a reference to the 'bool()' function. I hope that this helps. Happy coding!
14th Aug 2021, 4:42 AM
Calvin Thomas
Calvin Thomas - avatar
+ 2
Great, Thanks both of you
14th Aug 2021, 5:22 AM
Amol Bhandekar
Amol Bhandekar - avatar