single
Lambda Functions
Swipe to show menu
Lambda functions are anonymous functions, meaning they don't have a name. They are created using the lambda keyword and are often used to define short functions where you can specify a function on the spot.
The basic syntax of a lambda function is as follows:
lambda arguments: expression
lambda: the keyword indicating the start of a lambda function definition;arguments: the list of arguments the function takes;expression: the expression executed when the function is called. The result of the expression is returned as the function's value.
The key feature of lambda functions is their concise syntax. They are convenient when you need to define a simple function without writing a lot of code.
Single and Multiple Arguments
A lambda function can take one or more arguments:
1234567# Single argument square = lambda x: x**2 print(square(5)) # 25 # Multiple arguments add = lambda x, y: x + y print(add(3, 5)) # 8
Conditional Logic in Lambda Functions
You can use a ternary expression to add conditional logic inside a lambda:
123is_even = lambda x: "even" if x % 2 == 0 else "odd" print(is_even(4)) # "even" print(is_even(7)) # "odd"
Using Lambda with Built-in Functions
A common use case is combining lambda functions with built-in functions like map() and filter():
123456789prices = [100, 200, 300] # Apply 10% discount to each price discounted = list(map(lambda price: price * 0.9, prices)) print(discounted) # [90.0, 180.0, 270.0] # Keep only prices above 150 expensive = list(filter(lambda price: price > 150, prices)) print(expensive) # [200, 300]
You can also use max() inside a lambda to handle edge cases directly within the expression:
123safe_value = lambda x: max(x, 0) # Returns 0 if x is negative print(safe_value(-5)) # 0 print(safe_value(10)) # 10
Lambda functions are best suited for short, single-expression logic. If your function requires multiple lines or complex logic, a regular def function is a better choice.
Swipe to start coding
There is a list of prices (prices), and a lambda expression needs to be implemented that takes a price as a parameter and deducts 13% tax from it.
- Define a lambda expression using the
lambdakeyword. - The lambda expression should take one parameter (
price). - If the
priceis negative, consider it invalid and return 0 using themax()function directly within the lambda expression. - The lambda should first check the price and then deduct 13% from the valid amount.
- Use a list comprehension to apply
apply_taxto each element inprices.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat