+ 1

Error when using filter() in python

I have a written a small code in which I am trying to get only the even numbers from a list using the filter function. However I get an error message stating that 'int' object is not iterable. The function even() returns True if element in the list is even and false if it's opposite. This Boolean value will be used by the filter to sort even values into another variable called var. Then using for loop prints the elements in var.(this was my logic) list =[2,4,6,8,9,11] def even(list): for i in list: if i%2==0: return True else: return False var = filter(even,list ) for x in var: print(x)

19th Jun 2018, 9:01 AM
Sujith
3 Respostas
+ 2
the `filter` method passes one by one element to `even` and it filters the elements based on the return value of even(), so it should take a number as an input and not a list. Here is the modified code. lst =[2,4,6,8,9,11] def even(num): if num%2==0: return True else: return False var = filter(even, lst) for x in var: print(x)
19th Jun 2018, 9:30 AM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
+ 1
one thing you should note about filter is it only contains list of those elements where the result is true.
19th Jun 2018, 3:24 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
0
MslM
20th Feb 2020, 12:39 PM
يوسف البصراوي