⬅ Previous Topic
Map, Filter, ReduceNext Topic ⮕
Immutability and Pure Functions⬅ Previous Topic
Map, Filter, ReduceNext Topic ⮕
Immutability and Pure FunctionsLambda functions, also known as anonymous functions, are functions that are defined without a name. They are typically used for short, simple operations where defining a full function might feel excessive or unnecessary.
In programming, there are many cases where you need a function temporarily — for example, as an argument to another function. Lambda functions allow you to define small pieces of functionality inline without cluttering your codebase with lots of function definitions.
lambda (parameters): expression
This represents an unnamed function that accepts input via parameters
and returns the result of the expression
.
add = lambda (a, b): a + b
result = add(3, 5)
print(result)
Output:
8
Here, lambda (a, b): a + b
creates an anonymous function that takes two arguments and returns their sum. It is assigned to a variable add
so it can be reused like a regular function.
Why not just define a regular function with a name?
Answer: You can — and in many cases, you should. However, lambda functions are preferred when the function is small and used only once or within another function call like sorting, filtering, or mapping.
def apply_operation(operation, x, y):
return operation(x, y)
result = apply_operation(lambda (a, b): a * b, 4, 6)
print(result)
Output:
24
Here, instead of creating a separate function to multiply two numbers, we passed a lambda function directly as an argument to apply_operation
. This makes the code shorter and cleaner for simple tasks.
items = [(1, 'apple'), (3, 'banana'), (2, 'cherry')]
sorted_items = sort(items, key=lambda (item): item[1])
print(sorted_items)
Output:
[(1, 'apple'), (3, 'banana'), (2, 'cherry')]
The lambda function lambda (item): item[1]
tells the sort function to sort the list based on the second element of each tuple (the fruit name). This is a common use-case where lambda functions improve readability and maintainability.
map()
to apply a function to every item in a listfilter()
to select certain itemssort()
or sorted()
to define custom sorting logicCan a lambda function have multiple lines?
Answer: No. Lambda functions are limited to a single expression. For multiple statements or complex logic, use a regular function definition.
Lambda functions are powerful tools that allow concise expression of simple functions. While they are not a replacement for regular functions, they shine in situations where brevity and simplicity are valued, especially in functional programming contexts.
⬅ Previous Topic
Map, Filter, ReduceNext Topic ⮕
Immutability and Pure FunctionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.