Tip: Lambda functions are anonymous, single-expression functions useful for small calculations. They automatically return the result of the expression.
You need a lambda function that takes three numbers a, b, c and returns the largest number. Which of the following correctly does this?
This exercise tests understanding of lambda functions with multiple arguments and using conditional expressions.
Option 1: Incorrect. This sums the numbers instead of finding the largest.
Option 2: Incorrect. This returns the minimum, not the maximum number.
Option 3: Incorrect. Correct logic, but it is a normal function, not a lambda.
Option 4: Correct. Uses a lambda with conditional expressions to return the largest number among three.
Example usage:
largest_num = lambda a, b, c: a if a > b and a > c else b if b > c else c
print(largest_num(10, 20, 15)) # 20
print(largest_num(5, 3, 7)) # 7
Tip: Use lambda for inline functions, even with conditional expressions. Pay attention to the difference between normal functions and lambda, and ensure the logic matches the requirement.
Which of the following statements about Python lambda functions is TRUE?
This exercise tests conceptual understanding of Python lambda functions.
Option 1: Incorrect. Lambda functions cannot contain multiple statements such as loops, assignments, or multiple expressions. They are limited to a single expression.
Option 2: Correct. Lambda functions are anonymous functions that take any number of arguments but are restricted to a single expression, which is automatically returned.
Option 3: Incorrect. Lambda functions can take one or more arguments, just like normal functions.
Option 4: Incorrect. Lambda functions can be used immediately (inline) without assigning to a variable, e.g., (lambda x: x**2)(5).
Key Takeaways:
Lambda = anonymous, single-expression function.
Returns the value of the expression automatically.
Can take multiple arguments.
Can be used inline without assignment.
Tip: Conceptual questions like this help distinguish lambda from normal functions, especially their limitations and use cases.
Which of the following is the most appropriate scenario to use a lambda function in Python?
This exercise tests understanding of the practical use cases of lambda functions.
Option 1: Incorrect. Lambdas cannot contain multiple statements, loops, or assignments, so this is inappropriate.
Option 2: Incorrect. For reusable, complex functions, normal def functions are better because they are named, readable, and maintainable.
Option 3: Correct. Lambdas are ideal for creating small, one-line functions that can be used inline, for example, as an argument to another function.
Option 4: Incorrect. Lambdas cannot replace functions with multiple expressions or complex logic.
Key Takeaways:
Use lambdas for concise, one-line functions.
Great for passing as arguments to other functions or for temporary operations.
calc = lambda x, y, z: x*2 + y - z
print(calc(3, 5, 2)) # 9
print(calc(4, 2, 1)) # 9
Tip: When evaluating lambda expressions with multiple arguments, substitute values carefully and follow operator precedence. Multiplication comes before addition and subtraction.
Consider the following lambda:
f = lambda x: x % 2 == 0 and x > 10
What does f(12) return, and why?
This exercise tests understanding of lambda functions with boolean expressions and the and operator.
Option 1: Incorrect. 12 is greater than 10, so this statement is false.
Option 2: Correct. The lambda evaluates x % 2 == 0 (12 % 2 == 0 → True) and x > 10 (12 > 10 → True). Using and returns True only if both are True.
Option 3: Incorrect. Lambda returns the result of the expression, not the input.
Option 4: Incorrect. Lambdas can include multiple conditions using and or or.
Example usage:
f = lambda x: x % 2 == 0 and x > 10
print(f(8)) # False (even but not greater than 10)
print(f(12)) # True (even and greater than 10)
print(f(15)) # False (greater than 10 but not even)
Tip: In lambdas, boolean expressions return True or False. Combine conditions carefully using and / or for multi-part checks.
Which of the following statements about Python lambda functions is FALSE?
This exercise tests understanding of limitations and capabilities of lambda functions.
Option 1: Incorrect. Lambdas can take multiple arguments, just like normal functions.
Option 2: Incorrect. Lambdas can be returned from another function, making them useful for closures or dynamic behavior.
Option 3: Correct. Lambda functions are restricted to a single expression. They cannot contain multiple statements, loops, or assignments.
Option 4: Incorrect. Lambdas can be used as arguments to higher-order functions like sorted(), map(), etc.
Key Takeaways:
Lambdas are concise, single-expression functions.
Cannot contain statements like loops, multiple assignments, or complex multi-step logic.
Can be used inline, returned from functions, or passed as arguments.
Tip: A common beginner mistake is trying to include multiple statements in a lambda. Remember: single expression only!
You have a list of strings representing names:
names = ["alice", "Bob", "CHARLIE", "dave"]
You want a lambda function to capitalize only the first letter and make the rest lowercase, which can be used with map(). Which is correct?
This exercise tests understanding of using lambda functions for practical string transformations.
Option 1: Incorrect. x.upper() makes all letters uppercase, not just the first letter.
Option 2: Incorrect. x.lower() converts all letters to lowercase, losing the first letter capitalization.
Option 3: Incorrect. x.capitalize() and x.upper() returns the result of x.upper() due to and, not the intended transformation.
Option 4: Correct. x.capitalize() converts the first letter to uppercase and the rest to lowercase, exactly as required.
Tip: Lambdas are great for inline transformations like string formatting, mapping over lists, or quick computations without defining full functions.
Consider the following Python code:
def multiplier(n):
return lambda x: x * n
double = multiplier(2)
triple = multiplier(3)
result = double(triple(4))
What is the value of result?
This exercise tests understanding of nested lambdas and function returns, requiring careful tracing of execution.
Step 1: The function multiplier(n) returns a lambda that multiplies its input by n.
Step 2:double = multiplier(2) returns a lambda: lambda x: x * 2
Step 3:triple = multiplier(3) returns a lambda: lambda x: x * 3
Step 4: Evaluate triple(4):
4 * 3 = 12
Step 5: Evaluate double(triple(4)) → double(12):
12 * 2 = 24
Step 6: Final result is 24.
Example usage:
def multiplier(n):
return lambda x: x * n
double = multiplier(2)
triple = multiplier(3)
print(double(triple(4))) # 24
print(triple(double(4))) # 24 as well (4*2=8, 8*3=24)
Key Takeaways:
Functions can return lambdas, which can be stored and called later.
Nested calls require step-by-step evaluation to avoid mistakes.
Order of evaluation matters: inner lambda executes first.
Which of the following lambda functions will raise an error or behave unexpectedly?
This exercise tests understanding of lambda restrictions and error-prone patterns.
Option 1: Works. Using a mutable default argument is generally discouraged because it can accumulate changes across calls, but it does not raise an error. Example:
f = lambda x=[]: x.append(1) or x
print(f()) # [1]
print(f()) # [1, 1] - still works
Option 2: Incorrect / Error. y += x is a statement, and lambda functions cannot contain statements. Lambdas can only have a single expression. This will raise a SyntaxError.
Option 3: Works. Simply multiplies the input by 2.
Option 4: Works. Adds two numbers, with a default argument.
Key Takeaways:
Lambdas can only contain a single expression; statements like +=, if statements, or loops are not allowed.
Using mutable default arguments is allowed but can cause unexpected behavior if not carefully managed.
Always test complex lambdas to ensure they behave as intended.
You have a list of dictionaries representing students and their scores:
You want to create a lambda function inside map() to extract only the names of students who scored at least 80. Which of the following implementations is correct?
This exercise tests understanding of nested lambdas, filtering, and mapping in Python for practical data transformations.
Option 1: Incorrect. Syntax is invalid; Python requires else in a conditional expression inside lambda.
Option 2: Incorrect. Will return None for students with scores below 80, producing unwanted results in the mapped list.
Option 3: Incorrect. or is misused; it does not properly filter based on score.
Option 4: Correct. Uses filter() to select students with score ≥ 80, then map() to extract their names. Wrapping with list() returns the final list.
f = lambda x: (lambda y: y**2 if y % 2 == 0 else -(y**2))(x + 1)
g = lambda x: f(x) if x != 0 else 0
result = g(3) + g(-2) + g(1)
print(result) # 19
Key Takeaways:
Nested lambdas are evaluated from the inner expression outward.
Conditional expressions inside lambdas must be evaluated carefully.
Step-by-step calculation is essential when multiple variables and conditions are involved.
This demonstrates how lambdas can replace short multi-step functions but require careful reasoning.
A company keeps a record of employee performance scores. They want to classify employees based on a complex nested lambda logic. Consider the following Python code:
employees = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 70},
{"name": "Charlie", "score": 90},
{"name": "Dave", "score": 65},
]
classify = lambda emp: (lambda s: "Excellent" if s > 80 else ("Good" if s >= 70 else "Needs Improvement"))(emp["score"])
adjusted_scores = lambda emp_list: [(e["name"], classify(e)) if e["score"] % 2 == 0 else (e["name"], classify(e) + " - Review") for e in emp_list]
result = adjusted_scores(employees)
What is the value of result?
This exercise tests understanding of nested lambdas, conditional expressions, and list comprehensions in a real-world scenario.
Step 1: Understand classify:
classify = lambda emp:
(lambda s: "Excellent" if s > 80 else ("Good" if s >= 70 else "Needs Improvement"))(emp["score"])
It classifies employees as:
Score > 80 → "Excellent"
70 ≤ Score ≤ 80 → "Good"
Score < 70 → "Needs Improvement"
Step 2: Evaluate adjusted_scores:
adjusted_scores = lambda emp_list: [
(e["name"], classify(e)) if e["score"] % 2 == 0
else (e["name"], classify(e) + " - Review")
for e in emp_list]
- Employees with even scores get the **plain classification** - Employees with odd scores get **classification + " - Review"**
Option 4: Incorrect. `" - Passed"` is always appended to "D" due to missing parentheses; logic is wrong.
Example usage:
print(grade_student(92)) # A - Passed
print(grade_student(78)) # B - Passed
print(grade_student(62)) # C - Passed
print(grade_student(55)) # D - Failed
Key Takeaways:
Nested lambdas can be used for **multi-level decision logic**.
Use `.__str__()` or `str()` before string concatenation with numbers.
Pay attention to conditional logic inside lambdas and list comprehensions.
Multi-step transformations often require careful ordering of operations.
This style simulates real-world text processing, combining string and arithmetic logic.
Quick Recap of Python Lambda Functions Concepts
If you are not clear on the concepts of Lambda Functions, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
Python Lambda Functions — Overview
Lambda functions in Python are small, anonymous functions created using the lambda keyword. They are useful for quick, one-off operations without defining a full function with def.
Can be used without a name; optionally assign to a variable
Single Expression
Only one expression is allowed, no multiple statements
Implicit Return
Returns the value of the expression automatically
Compact
Reduces boilerplate for small functions
Example of a simple lambda function demonstrating compactness:
multiply = lambda a, b: a * b
print(multiply(4, 6)) # Output: 24
Python Lambda Function Syntax
The general syntax of a lambda function is:
lambda arguments: expression
Explanation:
arguments – comma-separated input parameters
expression – single operation whose result is returned automatically
Note: Lambda functions cannot include loops, multiple statements, or explicit return
Example of basic lambda usage:
square = lambda x: x ** 2
print(square(7)) # Output: 49
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Lambda Functions with Multiple Arguments
Lambda functions can accept more than one argument. Simply separate the arguments with commas.
# Lambda with two arguments
multiply = lambda a, b: a * b
print(multiply(4, 6)) # Output: 24
# Lambda with three arguments
maximum = lambda x, y, z: max(x, y, z)
print(maximum(12, 7, 19)) # Output: 19
Tip: Use descriptive variable names for clarity.
Nested Lambda Functions
You can create a lambda function that returns another lambda. This is useful for creating simple closures or higher-order functions.
# Lambda returning another lambda
power = lambda n: (lambda x: x ** n)
cube = power(3)
print(cube(5)) # Output: 125
# Another nested example
adder = lambda a: (lambda b: a + b)
add_five = adder(5)
print(add_five(10)) # Output: 15
Using Lambda for Conditional Expressions
Lambda functions can include a single-line if-else expression for quick conditional computations.
# Lambda with a conditional expression
sign = lambda x: "Positive" if x > 0 else "Non-positive"
print(sign(8)) # Output: Positive
print(sign(-3)) # Output: Non-positive
Assigning and Reusing Lambda Functions
You can assign a lambda function to a variable to reuse it like a normal function.
# Assigning lambda to a variable
area = lambda length, width: length * width
print(area(5, 10)) # Output: 50
print(area(7, 3)) # Output: 21
Practical Tips
Keep lambda functions simple and readable. For more complex logic, use regular functions.
# Keep lambda functions simple
add = lambda x, y: x + y
# For complex logic, use a regular function
def complex_operation(a, b):
if a > b:
return a - b
return b - a
Avoid overcomplicating lambdas; they are meant for simple tasks.
Use meaningful variable names for readability.
Combine with other Python features for practical use (closures, sorting, etc.).
Summary: Key Points About Python Lambda Functions
Lambda functions are anonymous, single-expression functions in Python.
They automatically return the result of the expression.
Can accept multiple arguments and even return other lambdas.
Best for short, one-off tasks; avoid complex logic inside lambdas.
Improves code brevity while keeping it readable.
Understanding lambdas is essential for writing clean, functional-style Python code.
Practicing Python Lambda Functions? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python – Lambda Functions
Welcome to Solviyo’s Python – Lambda Functions exercises, a practical collection designed to help learners master anonymous functions in Python. In this section, we focus on the core ideas behind lambda expressions, their syntax, usage with built-in functions like map, filter, and reduce, and real-world applications. These exercises come with clear explanations and answers so you can learn confidently and understand every concept step by step.
What You Will Learn
Through these exercises, you will explore how lambda functions simplify Python code and make it more readable, including:
Understanding what lambda functions are and how they differ from regular Python functions.
Writing concise, one-line functions using lambda expressions for quick computations.
Applying lambda functions in practical scenarios such as sorting, conditional expressions, and functional programming patterns.
Recognizing when to use lambda functions and when a named function might be more readable.
Exploring scope, arguments, and return values within lambda functions with hands-on exercises, explanations, and answers.
These exercises are designed to be approachable but practical, helping you understand not just how lambda functions work, but why they are a useful tool in Python programming. A Quick Recap section is also available for refreshing key concepts before practicing.
Why Learning Lambda Functions Matters
Lambda functions are widely used in Python, especially in data processing, functional programming, and coding interviews. Mastering them helps you write cleaner, more compact code and improves your ability to read complex Python scripts. By practicing with our exercises, MCQs, explanations, and answers, you will strengthen your understanding of anonymous functions, avoid common mistakes, and build confidence in using Python for real-world tasks and projects.
Start Strengthening Your Python Skills
With Solviyo’s Lambda Functions exercises, you can start practicing immediately with hands-on tasks and MCQs. Each question comes with explanations and answers so you can verify your learning as you go. Regular practice will help you grasp lambda functions thoroughly, making your Python code more concise, readable, and professional-ready. Dive in and boost your Python skills step by step!
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.