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
🌐
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 ...
Discussions

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
pandas - Python lambda function if else condition - Stack Overflow
Question: Trying to understand someone else's code. Can someone please explain what the lambda function is doing here?. Does the lambda function here translates to: If the first 3 digits of OrderNu... More on stackoverflow.com
🌐 stackoverflow.com
python - Lambda including if...elif...else - Stack Overflow
Nest if .. elses: lambda x: x*10 if x<2 else (x**2 if x<4 else x+10) More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
AskPython
askpython.com › home › lambda with conditional statements in python
Lambda With Conditional Statements in Python - AskPython
October 6, 2023 - We create a lambda object as conditional_lambda. Then, we store a variable x and expression as x/100 from and in joining with that our conditional statement lies. The statement says that if x is less than 20 divide it by 100 else print it as it is.
🌐
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
6 days ago - numbers = [1, 2, 3, 4, 5, 6, 7, ... 'Large'] [2, 4, 6, 8, 10] Lambda functions with conditional statements provide a powerful way to create concise, inline decision-making logic in Python....
🌐
Python Examples
pythonexamples.org › python-lambda-if-else
Python Lambda - If Else, Nested If Else
You can write an if else or nested if else inside Python lambda function, to conditionally choose values to be returned. In this tutorial, we write Python Lambda Functions with If Else and Nested If Else.
🌐
Medium
medium.com › @whyamit101 › using-pandas-lambda-if-else-0d8368b70459
Using pandas lambda if else. The biggest lie in data science? That… | by why amit | Medium
April 12, 2025 - If a certain condition is true, the code within the if block runs; otherwise, the code in the else block runs. Pairing this with a lambda function can make your data transformations quick and efficient.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › lambda-with-if-but-without-else-in-python
Lambda with if but without else in Python - GeeksforGeeks
July 23, 2025 - Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e.
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-lambda-anonymous-functions-filter-map-reduce
Python Lambda Functions - GeeksforGeeks
The lambda function takes x as input. It uses nested if-else statements to return "Positive," "Negative," or "Zero."
Published   4 days ago
🌐
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.
🌐
TutorialsPoint
tutorialspoint.com › lambda-with-if-but-without-else-in-python
Lambda with if but without else in Python
July 17, 2023 - The 'otherwise' clause may not always be necessary when using a 'if' statement inside of a lambda function, though. The 'else' clause is required by the syntax of the 'if' statement inside a lambda function in Python.
🌐
Delft Stack
delftstack.com › home › howto › python › python lambda if
if...else in Lambda Function Python | Delft Stack
February 25, 2025 - This tutorial provides a comprehensive guide on using if statements in lambda functions in Python. Learn how to create efficient and readable code with conditional expressions, nested if statements, and filtering techniques. Enhance your Python skills and discover practical examples to implement ...
🌐
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 …
🌐
Stack Overflow
stackoverflow.com › questions › 71260517 › python-lambda-function-if-else-condition › 71260558
pandas - Python lambda function if else condition - Stack Overflow
import sqlalchemy as sq import pandas as pd data_df = pd.read_csv('/dbfs/FileStore/tables/CustomerOrders.txt', sep=',', low_memory=False, quotechar='"', header='infer' , encoding='cp1252') data_df[OrderNumber] = data_df[OrderNumber].apply(lambda x: x if x[:3] != '486' and x[:3] != '561' and x[:1] != '8' else "") .............
Top answer
1 of 4
225

Nest if .. elses:

lambda x: x*10 if x<2 else (x**2 if x<4 else x+10)
2 of 4
50

I do not recommend the use of apply here: it should be avoided if there are better alternatives.

For example, if you are performing the following operation on a Series:

if cond1:
    exp1
elif cond2:
    exp2
else:
    exp3

This is usually a good use case for np.where or np.select.


numpy.where

The if else chain above can be written using

np.where(cond1, exp1, np.where(cond2, exp2, ...))

np.where allows nesting. With one level of nesting, your problem can be solved with,

df['three'] = (
    np.where(
        df['one'] < 2, 
        df['one'] * 10, 
        np.where(df['one'] < 4, df['one'] ** 2, df['one'] + 10))
df

   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

numpy.select

Allows for flexible syntax and is easily extensible. It follows the form,

np.select([cond1, cond2, ...], [exp1, exp2, ...])

Or, in this case,

np.select([cond1, cond2], [exp1, exp2], default=exp3)

df['three'] = (
    np.select(
        condlist=[df['one'] < 2, df['one'] < 4], 
        choicelist=[df['one'] * 10, df['one'] ** 2], 
        default=df['one'] + 10))
df

   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

and/or (similar to the if/else)

Similar to if-else, requires the lambda:

df['three'] = df["one"].apply(
    lambda x: (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10) 

df
   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

List Comprehension

Loopy solution that is still faster than apply.

df['three'] = [x*10 if x<2 else (x**2 if x<4 else x+10) for x in df['one']]
# df['three'] = [
#    (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10) for x in df['one']
# ]
df
   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15
🌐
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.
🌐
Mimo
mimo.org › glossary › python › lambda-function
Python Lambda Function: Syntax, Usage, and Examples
Python · Open in Mimo · Open in Mimo · Copy Code · import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data) df['Age Group'] = df['Age'].apply(lambda x: 'Young' if x < 30 else 'Adult') print(df) Use cases in data science include data filtering, transformations, and feature engineering.