Python Lambda Functions are small, anonymous functions defined using the lambda keyword. Unlike regular functions defined using def, lambda functions are typically used for short, throwaway operations where defining a full function might be unnecessary. Despite their simplicity, they are extremely powerful when used appropriately.
A lambda function in Python is a concise way to create anonymous functions. These functions can take any number of arguments but can only have one expression.
lambda arguments: expression
square = lambda x: x * x print(square(5)) # Output: 25
Lambda functions are best used for short operations that are not reused. Common use cases include:
numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x ** 2, numbers)) print(squared) # Output: [1, 4, 9, 16, 25]
numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # Output: [2, 4, 6]
students = [('Alice', 85), ('Bob', 92), ('Charlie', 78)] sorted_students = sorted(students, key=lambda student: student[1]) print(sorted_students) # Output: [('Charlie', 78), ('Alice', 85), ('Bob', 92)]
Aspect | Lambda Function | Regular Function |
---|---|---|
Syntax | lambda x: x+2 | def add(x): return x+2 |
Name | Anonymous (unless assigned) | Named |
Complexity | One-liner, simple logic | Can contain multiple lines and logic |
Use Case | Inline, temporary operations | Reusable, modular code |
# Invalid: cannot include statements lambda x: y = x + 1 # SyntaxError
You can use ternary operators within lambda functions to include basic conditional logic.
max_value = lambda a, b: a if a > b else b print(max_value(10, 20)) # Output: 20
Python Lambda Functions provide a quick and effective way to write small anonymous functions. They are best suited for short-term use, especially when passed as arguments to higher-order functions. However, they have limitations and should be used judiciously to maintain code readability and quality.
Copyrights © 2024 letsupdateskills All rights reserved