Lambda functions in Python, often referred to as anonymous functions, are small, one-time, unnamed function objects created using the keyword lambda. The lambda function can have any number of arguments, but can only have one expression. It is used when a function is required for a short period, and defining it in the standard manner using def would be overkill.
Syntax
lambda arguments: expression
This expression is executed and the result is returned.
Features of Lambda Functions
- Can have any number of arguments but only one expression: The expression is evaluated and returned.
- Lambda functions are syntactically restricted to a single expression: This means you can't have multiple statements or annotations, or a return statement as you would in a named function.
- Anonymous: They are not declared in the standard manner by using the
def keyword. You can use them without having to assign a name.
Uses of Lambda Functions
1. In conjunction with built-in functions
-
filter(): Filters items out of a sequence. Lambda functions can specify the filtering criteria.
my_list = [1, 2, 3, 4, 5, 6]
new_list = list(filter(lambda x: (x%2 == 0), my_list))
# Output: [2, 4, 6]
-
map(): Applies a function to all the items in an input list. Lambda functions can define the operation to apply.
my_list = [1, 2, 3, 4, 5, 6]
squared_list = list(map(lambda x: x**2, my_list))
# Output: [1, 4, 9, 16, 25, 36]
-
reduce() (from functools module): Performs a rolling computation to sequential pairs of values in a list.
from functools import reduce
my_list = [1, 2, 3, 4]
sum_list = reduce(lambda x, y: x+y, my_list)
# Output: 10
2. For small, one-time and inline function definitions
Lambda functions shine in scenarios where defining a full function is syntactically overkill. They're used extensively in data analysis and manipulation, especially with libraries like pandas and NumPy, where you often need small functions for transforming data.
3. In GUI frameworks
Lambda functions are used as callbacks for GUI frameworks, like Tkinter. They allow you to embed small functions into GUI component events without needing to define a separate function.
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Click me", command=lambda: print("Hello, World!"))
button.pack()
root.mainloop()
4. In sorting operations
Lambda functions are often used as the key argument in sorting functions/methods to specify a simple sorting criterion.
my_list = [('apple', 2), ('banana', 1), ('cherry', 3)]
sorted_list = sorted(my_list, key=lambda x: x[1])
# Output: [('banana', 1), ('apple', 2), ('cherry', 3)]
5. When working with pandas or NumPy
Lambda functions are used to apply operations over pandas DataFrame or Series and NumPy arrays.
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df['A_squared'] = df['A'].apply(lambda x: x**2)
# Adds a new column 'A_squared' with the square of column 'A'
Conclusion
Lambda functions provide a concise way to create small anonymous functions for quick and easy operations that require a function object. They are particularly useful in data manipulation, sorting, and scenarios where a simple function is needed temporarily without the overhead of defining a function using def. However, it's important to use them judiciously, as their overuse, especially for complex operations, can make the code harder to read and maintain.