4 4 Lambda Functions Explained
Key Concepts
Lambda functions in Python are small, anonymous functions defined with the lambda
keyword. They are useful for creating simple, one-line functions. The key concepts include:
- Definition and Syntax
- Usage in Expressions
- Comparison with Regular Functions
- Practical Applications
1. Definition and Syntax
A lambda function is defined using the lambda
keyword followed by a list of parameters, a colon, and an expression. The syntax is:
lambda parameters: expression
Example:
add = lambda x, y: x + y print(add(3, 5)) # Output: 8
2. Usage in Expressions
Lambda functions are often used in situations where a small function is needed for a short period. They can be used directly in expressions without being assigned to a variable.
Example:
print((lambda x, y: x * y)(4, 6)) # Output: 24
3. Comparison with Regular Functions
Lambda functions are similar to regular functions but are more concise and can only contain a single expression. Regular functions are defined using the def
keyword and can contain multiple statements.
Example of a regular function:
def multiply(x, y): return x * y print(multiply(4, 6)) # Output: 24
Example of a lambda function:
multiply = lambda x, y: x * y print(multiply(4, 6)) # Output: 24
4. Practical Applications
Lambda functions are commonly used with higher-order functions like map()
, filter()
, and sorted()
. They provide a concise way to apply functions to iterables.
Example with map()
:
numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x ** 2, numbers) print(list(squared)) # Output: [1, 4, 9, 16, 25]
Example with filter()
:
numbers = [1, 2, 3, 4, 5] evens = filter(lambda x: x % 2 == 0, numbers) print(list(evens)) # Output: [2, 4]
Example with sorted()
:
students = [("Alice", 22), ("Bob", 19), ("Charlie", 25)] sorted_students = sorted(students, key=lambda student: student[1]) print(sorted_students) # Output: [('Bob', 19), ('Alice', 22), ('Charlie', 25)]
Putting It All Together
By understanding and using lambda functions effectively, you can create concise and powerful code in Python. They are particularly useful in functional programming and when working with higher-order functions.
Example:
numbers = [1, 2, 3, 4, 5] result = map(lambda x: x * 2, filter(lambda x: x % 2 == 0, numbers)) print(list(result)) # Output: [4, 8]