Lambda Functions and Built-in Functional Tools
Python supports several tools for transforming, filtering, and summarizing collections. These are useful when preparing data for analysis.
Lambda Functions
A lambda function is a small anonymous function written as a single expression.
calculate_tax = lambda price: price * 0.18
print(calculate_tax(1000))
Lambda functions are useful for short operations, especially when another function expects a function as an argument. For more complex calculations, use a regular def function.
Using map()
The map() function applies a function to every element in an iterable.
prices = [100, 200, 300, 400]
taxed_prices = list(
map(lambda price: price * 1.18, prices)
)
print(taxed_prices)
Here, the lambda function calculates the price after adding 18% tax.
Using filter()
The filter() function selects elements that satisfy a condition.
ratings = [2.5, 4.2, 3.8, 4.8, 2.9]
good_ratings = list(
filter(lambda rating: rating >= 4.0, ratings)
)
print(good_ratings)
The result contains only ratings greater than or equal to 4.0.
Using sorted() with a Key
The sorted() function can sort complex collections according to a selected attribute.
products = [
{"name": "Mouse", "price": 700},
{"name": "Keyboard", "price": 1500},
{"name": "Monitor", "price": 12000}
]
sorted_products = sorted(
products,
key=lambda product: product["price"]
)
for product in sorted_products:
print(product["name"], product["price"])
This sorts the products by price in ascending order without changing the original list.
Python for Data Science
Vishalini A








