+ 1
Difference between x%2 and x%2 == 0
Can anyone please tell me how are below 2 bits of code being interpreted differently and giving different results: def check (x): return x%2 == 0 numbers = [11, 22, 33, 44, 55, 66] result = list(filter(check, numbers)) print(result) def check (x): return x%2 numbers = [11, 22, 33, 44, 55, 66] result = list(filter(check, numbers)) print(result)
5 Answers
+ 5
The filter() method constructs an iterator from elements of an iterable for which a function returns true
In first case it returns Boolean, returns true if x%2==0 and store that values else false and not stored the value
In second case the function returns 0 or 1 if odd number it returns 1 and if even returns 0
As true=1 and false=0
Which returns 1 it considered as true and stored it
+ 5
Filter returns items in sequence for which function returns True, in first case true: x%2=0, in second: x%2=1
0
But I did not specify x%2= 1 in second code and it still gives me the following result:
[11, 33, 55]
0
Thanks guys đ