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*

1st Jun 2021, 6:40 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
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
1st Jun 2021, 7:29 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
ChaoticDawg oh i had forgot about the modules operator, thank you mate.
1st Jun 2021, 7:33 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
1st Jun 2021, 6:47 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar