0

False condition

is there another way to invert the condition than lambda x: x%2 != 0 si if I want a list with all divisions by 2 not equal 0 can I write something like: not lambda x: x%2==0 instead of lambda x: x%2!=0 ?

11/19/2016 3:20:33 PM

Robin Hennaut

6 Answers

New Answer

+4

No you can't. "not" is a logical operator. It works only with "bool" type or smth that can be converted to boolean using "bool()" function. You can't negate the declaration of a function. You can only negate the returned value. For instance: >>> not lambda x: x%2 == 0 SyntaxError: invalid syntax >>> a = lambda x: x%2 == 0 >>> not a(3) True If you want a list with all odd numbers, as you have written, you can try list comprehention instead of map: >>> [n for n in range(10) if n%2] [1, 3, 5, 7, 9]

+3

Also you can rewrite it as lambda x: not x%2. Maybe that's what you wanted. >>> list(map(lambda x: not x%2, range(10))) [True, False, True, False, True, False, True, False, True, False] You can get a list of all odd numbers using map like this: >>> list(map(lambda x: x*2+1, range(5))) [1, 3, 5, 7, 9] Or like this (which is ugly): odds = [] list(map(lambda x: (odds.append(x) if x%2 else None), range(10))) print(odds) [1, 3, 5, 7, 9]

0

thanks that's what I wanted

0

no

0

no

0

no