What Lambda Function Meaning, Applications & Example
Anonymous function used in data processing pipelines.
What is Lambda Function?
A Lambda Function, in programming, is a small anonymous function defined without a name. It can accept any number of arguments but can only have a single expression. Lambda functions are often used for short-lived tasks and can be passed around as arguments to higher-order functions.
Syntax of Lambda Function
The basic syntax of a lambda function in Python is:
lambda arguments: expression
For example:
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
Applications of Lambda Functions
- Sorting: Lambda functions are frequently used with functions like
sorted()
to customize sorting logic. - Functional Programming: They are often used in functional programming paradigms for operations like
map()
,filter()
, andreduce()
. - Event Handling: Lambda functions are commonly used in event-driven programming, such as GUI applications.
Example of Lambda Function
A common example is using lambda for sorting a list of tuples by the second element:
data = [(1, 2), (3, 4), (5, 0)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data) # Output: [(5, 0), (1, 2), (3, 4)]