Lambda, Map, Filter
Lambda Functions¶
A lambda is a small, anonymous function. Use it when you need a quick calculation but don’t want to define a full def function.
Syntax: lambda input: output
# Standard function
def double(x):
return x * 2
# Lambda equivalent
double_lambda = lambda x: x * 2
print(double(5))
print(double_lambda(5)) Output
10
10
Map and Filter¶
map(function, list): Applies a function to every item.filter(function, list): Keeps items where the function is True.
harvests = [100, 200, 50, 0, 300]
# 1. Map: Convert kg to tons (divide by 1000)
tons_iterator = map(lambda x: x / 1000, harvests)
print(f"Tons: {list(tons_iterator)}")
# 2. Filter: Remove zero production
active_farms = filter(lambda x: x > 0, harvests)
print(f"Active Harvests: {list(active_farms)}")Output
Tons: [0.1, 0.2, 0.05, 0.0, 0.3]
Active Harvests: [100, 200, 50, 300]