0
How to use filter in Python?
How do i use the filter method to return a list of certain elements that match a condition. Example nums = [1,2,3,4,5,6,7,8,9] new_list = list(filter (lambda x: x / 2 == 0, nums)) But that returns a empty list. *Correct my code*
3 Réponses
+ 2
David Holmes Ng'andu
He's saying you are dividing by 2 instead of checking to see if the number is divisible by 2.
x / 2 == 0
Vs
x % 2 == 0
If x = 4 the first will result in;
4 / 2 == 0
# 4 divided by 2 equals 2
2 == 0
False
The only way the above would be true is if x == 0
Where the second checks the remainder from division by 2.
4 % 2 == 0
# 4 divided by 2 equals 2 with a remainder of 0
0 == 0
True
+ 1
ChaoticDawg oh i had forgot about the modules operator, thank you mate.
0
Jan Markus huh?