Python
Lambda
Conditional Statements
Programming
Code Duplicate

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Yes, Python lambdas support conditional logic using the ternary expression x if condition else y. This is the only way to branch inside a lambda because lambdas are limited to a single expression — they cannot contain statements like if: blocks, for loops, or assignments. For anything more complex than a simple ternary, use a regular def function instead.

Basic Ternary in Lambda

python
1# Ternary syntax: value_if_true if condition else value_if_false
2classify = lambda x: "positive" if x > 0 else "non-positive"
3
4print(classify(5))    # "positive"
5print(classify(-3))   # "non-positive"
6print(classify(0))    # "non-positive"

This is equivalent to:

python
1def classify(x):
2    if x > 0:
3        return "positive"
4    else:
5        return "non-positive"

Chained Conditions (elif Equivalent)

Nest ternary expressions for multiple conditions:

python
1grade = lambda score: (
2    "A" if score >= 90 else
3    "B" if score >= 80 else
4    "C" if score >= 70 else
5    "D" if score >= 60 else
6    "F"
7)
8
9print(grade(95))  # "A"
10print(grade(85))  # "B"
11print(grade(72))  # "C"
12print(grade(55))  # "F"

Parentheses are optional but improve readability. Python evaluates left to right, returning the first matching value.

Using Lambda with Built-in Functions

python
1numbers = [1, -2, 3, -4, 5, -6]
2
3# filter with condition
4positives = list(filter(lambda x: x > 0, numbers))
5print(positives)  # [1, 3, 5]
6
7# map with conditional transformation
8abs_values = list(map(lambda x: x if x >= 0 else -x, numbers))
9print(abs_values)  # [1, 2, 3, 4, 5, 6]
10
11# sorted with conditional key
12words = ["banana", "Apple", "cherry", "Date"]
13sorted_words = sorted(words, key=lambda w: w.lower())
14print(sorted_words)  # ['Apple', 'banana', 'cherry', 'Date']

Lambda with and/or (Short-Circuit)

An older pattern uses and/or for branching. This works but is less readable:

python
1# Using and/or — NOT recommended
2f = lambda x: x > 0 and "positive" or "non-positive"
3print(f(5))   # "positive"
4print(f(-3))  # "non-positive"
5
6# BUG: fails when the "true" value is falsy
7g = lambda x: x > 0 and 0 or "non-positive"
8print(g(5))   # "non-positive" — WRONG! 0 is falsy, so 'or' continues

Always use the ternary expression (if/else) instead of and/or — it handles all values correctly.

Practical Examples

Default Values

python
1# Return value or default if None
2get_name = lambda user: user.get("name") if user.get("name") else "Anonymous"
3
4# Simpler with 'or'
5get_name = lambda user: user.get("name") or "Anonymous"

Clamping Values

python
1clamp = lambda val, lo, hi: lo if val < lo else hi if val > hi else val
2
3print(clamp(5, 0, 10))    # 5
4print(clamp(-3, 0, 10))   # 0
5print(clamp(15, 0, 10))   # 10

Type-Based Processing

python
1process = lambda x: x.strip() if isinstance(x, str) else str(x)
2
3print(process("  hello  "))  # "hello"
4print(process(42))            # "42"

Sorting with Conditional Logic

python
1data = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": None}, {"name": "Charlie", "age": 25}]
2
3# Sort by age, putting None values at the end
4sorted_data = sorted(data, key=lambda d: (d["age"] is None, d["age"] if d["age"] is not None else 0))
5print([d["name"] for d in sorted_data])  # ['Charlie', 'Alice', 'Bob']

What Lambdas Cannot Do

python
1# CANNOT use statements (if:, for:, while:, =, etc.)
2# These all cause SyntaxError:
3
4# lambda x: if x > 0: return x     # No if statements
5# lambda x: x = x + 1              # No assignments
6# lambda x: for i in x: print(i)   # No for loops
7# lambda x: import math             # No imports
8
9# Instead, use a regular function:
10def process(x):
11    if x > 0:
12        result = x * 2
13    else:
14        result = 0
15    return result

When to Use Lambda vs def

python
1# GOOD — short, simple, used once
2sorted(items, key=lambda x: x.name)
3filter(lambda x: x > 0, numbers)
4map(lambda x: x ** 2, numbers)
5
6# BAD — too complex, assign to a variable
7# PEP 8 says: don't assign lambdas to variables, use def instead
8double = lambda x: x * 2  # Don't do this
9
10# Do this instead:
11def double(x):
12    return x * 2

PEP 8 recommends using def whenever you would assign a lambda to a name. Lambdas are best used inline as arguments to functions like sorted(), map(), and filter().

Common Pitfalls

  • Multi-line logic in lambda: Lambdas only support a single expression. If you need multiple statements, try/except, or assignments, use def. No amount of ternary nesting replaces a proper function.
  • Readability of nested ternaries: lambda x: "a" if x > 0 else "b" if x == 0 else "c" is hard to read. Beyond two conditions, use a def function or a dictionary lookup.
  • and/or for branching: x and a or b fails when a is falsy (0, empty string, None). Always use a if x else b instead.
  • Lambda in loops: [lambda: i for i in range(5)] creates 5 lambdas that all return 4 (the final value of i). Fix with default arguments: [lambda i=i: i for i in range(5)].
  • Assigning lambdas: f = lambda x: x + 1 is valid but discouraged by PEP 8. The lambda's traceback shows <lambda> instead of a function name, making debugging harder.

Summary

  • Use value_if_true if condition else value_if_false for conditionals in lambda
  • Chain ternary expressions for multiple conditions (elif equivalent)
  • Lambdas only support expressions, not statements — no if:, for:, or assignments
  • Best used inline with sorted(), map(), filter(), and similar functions
  • Use def for anything with more than one condition or any complex logic
  • PEP 8 discourages assigning lambdas to variables — use def instead

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.