Explain Codes LogoExplain Codes Logo

Is there a way to perform "if" in python's lambda?

python
lambda
functions
conditional-statements
Anton ShumikhinbyAnton Shumikhin·Dec 20, 2024
TLDR

Lambda functions in Python are capable of emulating an "if" statement using the ternary operator: lambda x: <true_value> if <condition> else <false_value>. Consider the following example that classifies a number as being even or odd:

# Returns "Even" if the number is divisible by 2; else, it's definitely up to some "Odd" behavior. lambda x: "Even" if x % 2 == 0 else "Odd"

This code effectively means: return "Even" if x % 2 == 0, otherwise return "Odd". Simple and neat!

Do's and Don'ts with lambda

Be concise, be simple

Lambda functions are all about brevity and simplicity. You might be tempted to fit a classic print statement inside a lambda, but that's a forbidden fruit. Such structures just don't mix well with lambda, which is aimed to handle simple expressions.

To display output from lambda, consider sys.stdout.write.

If lambda could raise an Exception...

As you've already noticed, we're missing our good old friend raise inside a lambda. However, there's a workaround:

lambda x: x if x == 2 else (_ for _ in ()).throw(ValueError("Not 2")) # When you see a ValueError inside a lambda, you know someone messed with the Matrix!

Here, the exceptional logic sneakily piggybacks on a generator's throw() method. But remember, readability is key, so handling exceptions outside of lambdas is usually a smarter move.

When to use conditional lambdas

Quick data checks

A classic use case for a conditional lambda function is straightforward data validation, like checking if a piece of string contains only alphabets, and mapping it to a verdict:

lambda x: 'Valid' if x.isalpha() else 'Invalid' # Very judgmental lambda, huh?

Real-time calculations

Lambda functions come handy when you need to perform some real-time calculations on the fly. They become superheroes when paired with built-in functions such as map() and filter():

list(filter(lambda x: x > 5, range(10))) # Filters out those who are not 'above 5'. No prejudice, purely mathematical!

A one-time wonder

Lambda functions are also perfect for those quick, one-time used functions that are needed as callbacks:

sorted(list_of_dicts, key=lambda x: x['priority']) # Sorting those tasks out, like a boss!

What to avoid with lambda

Resist the dark side of complexity!

Much like Yoda advises Luke in Star Wars, you must resist the temptation of the dark side; don't give in to squeezing complex logic within a humble lambda. It loses readability and maintainability.

No Robot Dancing!

Multiple twisting and turning with if-else clauses within a lambda function will make it look like an elaborate dance move. It's fun to dance, but not here. Please, keep code as Waltz, not Breakdance.

Debugging: The final boss

Debugging lambdas is like playing a hard level of a videogame. As anonymous functions, they usually accept the mission and choose to erase their identity, making debugging a bit tricky. Named functions are your ally in such scenarios.

Advanced lambda with conditions

Function returns

A lambda can even change its mood and return different functions based on a condition. Interesting, isn't it?

lambda x: (lambda y: y+1) if x == 1 else (lambda y: y-1) # A lambda delivering lambdas! It's lambda-ception, folks!

Quick decisions

Guess what? you can use and and or for sneaky quick conditional checks inside a lambda too:

lambda x: (x > 3 and 'High') or 'Low' # It's like high score or low score, there's no mid score.

Just like an if-else statement, this will return 'High' if x > 3, else it will go for the 'Low' score.