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.

Answer from Robert Rossney on Stack Overflow
🌐
Pythonspot
pythonspot.com › python-lambda
python lambda if - Python Tutorial
For example, if you have the list [1,3,10,4,1] it will return 10 because at some point it will compare 'x=3, y=10: if (3 > 10) return 3 else return 10'. The program keeps repeating the statement 'x if (x > y) else y' until it cannot be applied further.
Discussions

Python lambda with if but without else - Stack Overflow
I was writing some lambda functions and couldn't figure this out. Is there a way to have something like lambda x: x if (x b) else b works ok. So far lam... More on stackoverflow.com
🌐 stackoverflow.com
can I use an if statement with a lambda function?
It helps to debug if you split your 1 liner into multiple variable steps at each function. I haven't worked with python but it appears the problem may be in your last map. It appears what you want is to filter for len(x['pdd_list']) == 0 in a filter function. .map(lambda x: x['pdd_list']) . filter(lambda x: len(x['pdd_list'])==0) More on reddit.com
🌐 r/apachespark
4
4
August 12, 2019
Using the if, else statement with reduce() and lambda()
Stefan Vaziri is having issues with: I think I got the beginning portion with reduce and lambda right. I think you need to use the if statement here but I'm not sure how to incorpor... More on teamtreehouse.com
🌐 teamtreehouse.com
3
February 24, 2016
Lambda if statement
You may be better just writing a normal function if it gets too complicated to understand, but for the sake of learning: something['SomeVariable'].apply(lambda x: dosomething() if isinstance(x, str) else dosomethingelse()) More on reddit.com
🌐 r/learnpython
9
6
August 18, 2015
Top answer
1 of 8
120

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.

2 of 8
28

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
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python lambda using if else
Python Lambda using if else - Spark By {Examples}
May 31, 2024 - The lambda should have only one expression so here, it should be if-else. The if returns the body when the condition is satisfied, and the else body is returned when the condition is not satisfied.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-use-if-else-elif-in-python-lambda-functions
How to use if, else & elif in Python Lambda Functions - GeeksforGeeks
July 23, 2025 - # Use if-else in Lambda Functions # check if two numbers is equal or greater or lesser result = lambda x,y : f"{x} is smaller than {y}" \ if x < y else (f"{x} is greater than {y}" if x > y \ else f"{x} is equal to {y}") # print for numbers ...
🌐
Kanoki
kanoki.org › 2022 › 09 › 12 › python-lambda-if-else-elif-with-multiple-conditions-and-filter-list-with-conditions-in-lambda
python lambda if, else & elif with multiple conditions and filter list with conditions in lambda | kanoki
September 12, 2022 - We could also use lambda to loop over a list and evaluate a condition · Let’s define a function with all the conditions that we want to evaluate · def f(grade): if grade > 7: return 'A+' elif grade >= 5 and grade <= 7: return 'A' elif grade <5: return 'B' else: return False ... DataFrames are a powerful tool for working with data in Python, and Pandas provides a number of ways to count duplicate rows in a DataFrame.
Find elsewhere
🌐
ProjectPro
projectpro.io › blog › how to apply lambda functions to python pandas?
How To Apply Lambda Functions To Python Pandas?
October 28, 2024 - For example, the following Lambda if-else Pandas function checks if a value is less than 1000000 and returns "Small" if it is or "Large" if it is not-
🌐
W3Schools
w3schools.com › python › python_lambda.asp
Python Lambda
Python If Python Elif Python Else Shorthand If Logical Operators Nested If Pass Statement Code Challenge Python Match ... Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Code Challenge Python Range
🌐
W3Schools
w3schools.com › python › python_conditions.asp
Python If Statement
Python can evaluate many types of values as True or False in an if statement. Zero (0), empty strings (""), None, and empty collections are treated as False. Everything else is treated as True.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Lambda Expressions in Python | note.nkmk.me
August 19, 2023 - Conditional expression (ternary operator) in Python · get_odd_even = lambda x: 'even' if x % 2 == 0 else 'odd' print(get_odd_even(3)) # odd print(get_odd_even(4)) # even · source: lambda_example.py · If you assign a name to a lambda expression as shown in the previous examples, the code checker may issue a warning.
🌐
GeeksforGeeks
geeksforgeeks.org › python › using-apply-in-pandas-lambda-functions-with-multiple-if-statements
Using Apply in Pandas Lambda functions with multiple if statements - GeeksforGeeks
June 20, 2025 - Lambda supports only a single if-else, not chained conditions. You can't use elif inside a lambda like in regular Python.
🌐
Python Morsels
pythonmorsels.com › lambda-expressions
Python's lambda functions - Python Morsels
October 25, 2023 - So lambda functions can only execute a single Python expression and their return value will be the result of that single expression. So how do lambda functions compare to traditional functions, in terms of costs and benefits? Well, it depends on how you categorize differences. If I had to classify the pros and cons of using lambda over def, I'd say:
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 documentation
There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif …
🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › building lambda functions with python
Building Lambda functions with Python - AWS Lambda
It relays any logs that your function outputs during invocation. If your function returns an error, Lambda formats the error and returns it to the invoker. ... The version of the AWS SDK included in the Python runtime depends on the runtime version and your AWS Region.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-use-if-else-amp-elif-in-python-lambda-functions
How to use if, else & elif in Python Lambda Functions
July 25, 2023 - As you can see in the output above, the lambda function with the if?else statement correctly determines whether a number is even or odd based on the condition we provided. This concise and small form allows us to handle such simple decision?making processes effectively. Now that we?ve understood if, and else in Python lambda functions, let?s move to the next section of this article to learn how to use multiple if else or elif in the lambda functions.
🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › building lambda functions with python › define lambda function handler in python
Define Lambda function handler in Python - AWS Lambda
January 31, 2026 - For example, AWS Lambda console uses the RequestResponse invocation type, so when you invoke the function on the console, the console will display the returned value. If the handler returns objects that can't be serialized by json.dumps, the runtime returns an error. If the handler returns None, as Python functions without a return statement implicitly do, the runtime returns null.
🌐
Programiz
programiz.com › python-programming › anonymous-function
Python Lambda/ Function (With Examples)
In this tutorial, we'll learn about Python lambda functions with the help of examples.