Lambda functions are ideal when a function is used only once and does not require a name. They provide a concise way to define small, one-time-use functions.
For example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# use lambda function because it is used only once
even_numbers = filter(lambda num: num % 2 == 0, numbers)
In this example, the lambda function filters out even numbers from the list. Since it’s only used once, a lambda function is a suitable choice.
However, if you need to reuse a function in various parts of your code, it’s better to define a named function.
# use named function because it is used multiple times
def is_even(num: int):
return num % 2 == 0
even_numbers = filter(is_even, numbers)
any(is_even(num) for num in numbers)
True
In this example, the is_even
function is defined by a name and is used multiple times. This approach avoids repeating the same code and makes your code more maintainable.