PYTHON
Efficient Filtering and Transformation with List Comprehensions
Learn to efficiently filter and transform lists of data using Python's concise list comprehensions, improving readability and performance for web applications.
products = [
{"id": 1, "name": "Laptop", "price": 1200, "active": True},
{"id": 2, "name": "Mouse", "price": 25, "active": False},
{"id": 3, "name": "Keyboard", "price": 75, "active": True},
{"id": 4, "name": "Monitor", "price": 300, "active": True}
]
# Filter active products and extract their names and prices, adding a tax
active_product_details = [
{"name": p["name"], "price_with_tax": round(p["price"] * 1.05, 2)}
for p in products if p["active"]
]
# Output:
# [
# {'name': 'Laptop', 'price_with_tax': 1260.0},
# {'name': 'Keyboard', 'price_with_tax': 78.75},
# {'name': 'Monitor', 'price_with_tax': 315.0}
# ]
print(active_product_details)
How it works: List comprehensions offer a concise and Pythonic way to create new lists by applying transformations and filters to existing iterables. This snippet demonstrates how to filter a list of product dictionaries based on an 'active' status and then transform the remaining items to include only specific fields ('name') and calculated values ('price_with_tax'), making data processing highly efficient and readable.