The syntax you're looking for:
lambda x: True if x % 2 == 0 else False
But you can't use print or raise in a lambda.
The syntax you're looking for:
lambda x: True if x % 2 == 0 else False
But you can't use print or raise in a lambda.
why don't you just define a function?
def f(x):
if x == 2:
print(x)
else:
raise ValueError
there really is no justification to use lambda in this case.
Lambda if statement
if statement - if and else in python lambda expression - Stack Overflow
can I use an if statement with a lambda function?
If statement in lambdas Python - Stack Overflow
Hello,
I'm trying to do a lambda statement where I check the type of the value, how do I implement if in lambda?
something['SomeVariable'].apply(lambda x: <if isinstance(x, str) = true, dosomething>)
First, let's remove this line as it doesn't do anything:
lambda x: 'big' if x > 100 else 'small'
This lambda expression is defined but never called. The fact that it's argument is also called x has nothing to do with the rest of the code.
Let's look at what remains:
a = 4
b = 7
x = lambda: a if 1 else b
print(x())
Here x becomes a function as it contains code. The lambda form can only contain expressions, not statements, so it has to use the expression form of if which is backward looking:
true-result if condition else false-result
In this case the condition is 1, which is always true, so the result of the function x() is always the value of a, assigned to 4 earlier in the code. Effectively, x() acts like:
def x():
return a
Understanding the differences between expressions and statements is key to understanding code like this.
Your x is always equals to 4, as it takes no arguments and if 1 is always True.
Then you have lambda expression that's not assigned to any variable, neither used elsewhere.
Eventualy, you print out x, which is always 4 as I said above.
P.S. I strongly suggest you to read Using lambda Functions from Dive into Python
writing an if statement with a lambda function:
I'm trying to filter a map in spark using an if statement but get a syntax error. I have not been able to find the error. Can you guys tell me what I am doing wrong here?
full_count_with0val = full_rdd.map(lambda x: json.loads(x[1])).flatMap(lambda x: x['exposures']).map(lambda x: x['pdd_list'] if len(x['pdd_list'])==0).take(5)
If you want to filter out all the strings that have 'cat' in them, then just use
>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda x: not 'cat' in x.lower(), cells)
['Dog', 'Snake', 'Lion']
If you want to keep those that have 'cat' in them, just remove the not.
>>> filter(lambda x: 'cat' in x.lower(), cells)
['Cat']
You could use a list comprehension here too.
>>> [elem for elem in cells if 'cat' in elem.lower()]
['Cat']
The element means the elements of the iterable. You just need to compare.
>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda element: 'Cat' == element, cells)
['Cat']
>>>
Or if you want to use in to test whether the element contains something, don't use if. A single if expression is syntax error.
>>> filter(lambda element: 'Cat' in element, cells)
['Cat']
>>>
Use the exp1 if cond else exp2 syntax.
rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T)
Note you don't use return in lambda expressions.
The right way to do this is simple:
def rate(T):
if (T > 200):
return 200*exp(-T)
else:
return 400*exp(-T)
There is absolutely no advantage to using lambda here. The only thing lambda is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.
The rate function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).
From a comment:
Well the function needed to fit in one line, which i didn't think you could do with a named function?
I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:
>>> def foo(x): return x + 1
Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.
Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval so you can use them, you actually just want to pass Python functions around as functions and use them as functions.
But on the off chance that this really is what you need here: Just use exec instead of eval.
You didn't mention which version of Python you're using. In 3.x, the exec function has the exact same signature as the eval function:
exec(my_function_string, my_globals, my_locals)
In 2.7, exec is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.
In earlier 2.x (before 2.6, I think?) you have to do it like this instead:
exec my_function_string in my_globals, my_locals
You are missing an else before 'O'. This works:
y = lambda symbol: 'X' if symbol==True else 'O' if symbol==False else ' '
However, I think you should stick to Adam Smith's approach. I find that easier to read.
You can use an anonymous dict inside your anonymous function to test for this, using the default value of dict.get to symbolize your final "else"
y = lambda sym: {False: 'X', True: 'Y'}.get(sym, ' ')