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.

Answer from Cristian Lupascu on Stack Overflow
🌐
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 › how-to-use-if-else-elif-in-python-lambda-functions
How to use if, else &amp; elif in Python Lambda Functions - GeeksforGeeks
July 23, 2025 - The lambda function will return a value for every validated input. Here, if block will be returned when the condition is true, and else block will be returned when the condition is false.
🌐
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 - If we try to add multiple if-elif-else blocks inside a lambda expression then it causes syntax errors. Example that will break and cause syntax error: ... Lambda supports only a single if-else, not chained conditions.
🌐
thisPointer
thispointer.com › home › functions › python : how to use if, else & elif in lambda functions
Python : How to use if, else & elif in Lambda Functions - thisPointer
April 30, 2023 - # Lambda function with if, elif & else i.e. # If the given value is less than 10 then Multiplies it by 2 # else if it's between 10 to 20 the multiplies it by 3 # else returns the unmodified same value converter = lambda x : x*2 if x < 10 else ...
🌐
Python Examples
pythonexamples.org › python-lambda-if-else
Python Lambda - If Else, Nested If Else
You can have nested if else in lambda function. Following is the syntax of Python Lambda Function with if else inside another if else, meaning nested if else.
🌐
AskPython
askpython.com › python › examples › lambda-with-if-else-conditions
Lambda With Conditional Statements in Python - AskPython
December 31, 2021 - 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.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python lambda using if else
Python Lambda using if else - Spark By {Examples}
May 31, 2024 - How to use an if else in Python lambda? You can use the if-else statement in a lambda as part of an expression. The lambda should have only one expression
Find elsewhere
🌐
Iditect
iditect.com › faq › python › multiple-if-statements-in-a-lambda-function-in-python.html
Multiple if statements in a lambda function in python
Description: Python lambda functions can contain multiple if statements using the ternary conditional operator. Here's an example demonstrating the syntax for a lambda function with two if statements. # Lambda function with multiple if statements func = lambda x: 'even' if x % 2 == 0 else 'odd' ...
🌐
Delft Stack
delftstack.com › home › howto › python › python lambda if
if...else in Lambda Function Python | Delft Stack
February 25, 2025 - Here’s how you can implement this: nested_if_lambda = lambda x: "Positive" if x > 0 else ("Negative" if x < 0 else "Zero") result1 = nested_if_lambda(10) result2 = nested_if_lambda(-5) result3 = nested_if_lambda(0) ...
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
🌐
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
March 27, 2026 - get_grade = lambda score: "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D" if score >= 60 else "F" print(get_grade(95)) print(get_grade(85)) print(get_grade(75)) print(get_grade(65)) print(get_grade(45))
Top answer
1 of 2
6

Apply across columns

Use pd.DataFrame.apply instead of pd.Series.apply and specify axis=1:

df['one'] = df.apply(lambda row: row['one']*100 if row['two']>8 else \
                     (row['one']*1 if row['two']<8 else row['one']**2), axis=1)

Unreadable? Yes, I agree. Let's try again but this time rewrite as a named function.

Using a function

Note lambda is just an anonymous function. We can define a function explicitly and use it with pd.DataFrame.apply:

def calc(row):
    if row['two'] > 8:
        return row['one'] * 100
    elif row['two'] < 8:
        return row['one']
    else:
        return row['one']**2

df['one'] = df.apply(calc, axis=1)

Readable? Yes. But this isn't vectorised. We're looping through each row one at at at time. We might as well have used a list. Pandas isn't just for clever table formatting, you can use it for vectorised calculations using arrays in contiguous memory blocks. So let's try one more time.

Vectorised calculations

Using numpy.where:

df['one'] = np.where(row['two'] > 8, row['one'] * 100,
                     np.where(row['two'] < 8, row['one'],
                              row['one']**2))

There we go. Readable and efficient. We have effectively vectorised our if / else statements. Does this mean that we are doing more calculations than necessary? Yes! But this is more than offset by the way in which we are performing the calculations, i.e. with well-defined blocks of memory rather than pointers. You will find an order of magnitude performance improvement.

Another example

Well, we can just use numpy.where again.

df['one'] = np.where(df['name'].isin(['a', 'b']), 100, df['two'])
2 of 2
1

you can do

df.apply(lambda x: x["one"] + x["two"], axis=1)

but i don't think that such a long lambda as lambda x: x["one"]*100 if x["two"]>8 else (x["one"]*1 if x["two"]<8 else x["one"]**2) is very pythonic. apply takes any callback:

def my_callback(x):
    if x["two"] > 8:
        return x["one"]*100
    elif x["two"] < 8:
        return x["one"]
    else:
        return x["one"]**2

df.apply(my_callback, axis=1)
🌐
GeeksforGeeks
geeksforgeeks.org › lambda-with-if-but-without-else-in-python
Lambda with if but without else in Python - GeeksforGeeks
October 6, 2021 - Syntax: lambda variable : expression Where, variable is used in the exp ... Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned.
🌐
OpenGenus
iq.opengenus.org › python-lambda-if-else
Python lambda if else
November 27, 2022 - As an alternative, place a default value or NoneType in else part of the Lambda function in Python. The idea of using if else elif in Lambda is to add another if else part in the else part of the one line alternative of if else in Python.
🌐
Eikke
eikke.com › python-ifelse-in-lambda › index.html
Python if/else in lambda – Ikke's blog
(This would return the string “big number” if x was greater than 100, and “little number” otherwise.) Sometimes I get around this by defining my own if_else that I can use in lambda-functions: def if_else(condition, a, b) : if condition : return a else : return b · Actually, you don’t need this helper if_else function at all:
🌐
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 - You can nest if statements within your lambda function to handle multiple conditions. How do I apply a lambda function to an entire DataFrame? You can use the .apply() method combined with your lambda function to apply it to an entire DataFrame ...
🌐
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 "") .............
🌐
Stack Overflow
stackoverflow.com › questions › 64088275 › using-an-if-else-statement-inside-a-for-statement-inside-lambda-statement
python - Using an if else statement inside a for statement inside lambda statement - Stack Overflow
So i know that this work : fac = lambda x: [element for element in x] and this also work : fac = lambda x: x*fac(x-1) if x!=0 else 1 but why this is not working : fac = lambda *x : [ n * fac(n-1...