Lambda Expression in Python
Lambda functions in Python are small anonymous functions defined using the
lambda keyword. They are commonly used for short, simple operations
where defining a full function using def is unnecessary.
What is a Lambda Function?
A Lambda function is a one-line function without a name. It can take multiple arguments but can contain only one expression.
lambda arguments: expression
Basic Example
# Normal function
def add(a, b):
return a + b
print(add(5, 3))
Using Lambda
add = lambda a, b: a + b print(add(5, 3))
The Lambda version is shorter and cleaner for simple logic.
Lambda with Single Argument
square = lambda x: x * x print(square(4))
Lambda with Multiple Arguments
multiply = lambda x, y, z: x * y * z print(multiply(2, 3, 4))
Using Lambda with Built-in Functions
1. map()
numbers = [1, 2, 3, 4] squares = list(map(lambda x: x * x, numbers)) print(squares)
2. filter()
numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers)
3. sorted()
students = [("Chandan", 25), ("Amit", 22), ("Ravi", 24)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
Advantages of Lambda Function
- Short and concise code
- Useful for temporary functions
- Improves readability in functional programming
- Commonly used with map(), filter(), and reduce()
Limitations of Lambda
- Only one expression is allowed
- Cannot contain multiple statements
- Not suitable for complex logic
Lambda vs Normal Function
- Lambda: Anonymous, single expression, used for short tasks
- Normal Function: Named, can contain multiple statements, suitable for complex logic
Conclusion
Lambda expressions are powerful tools in Python that help write concise and functional-style code. They are best suited for short operations and are frequently used with higher-order functions like map(), filter(), and sorted(). Mastering Lambda functions will improve your efficiency in Python programming.
No comments:
Post a Comment