PYTHON
Filter and Transform Data with Python List Comprehensions
Master list comprehensions to concisely filter and transform data from API responses or database queries, improving code readability and performance in Python web apps.
products = [
{"id": 101, "name": "Wireless Mouse", "price": 25.00, "in_stock": True},
{"id": 102, "name": "Mechanical Keyboard", "price": 75.00, "in_stock": False},
{"id": 103, "name": "Webcam", "price": 49.99, "in_stock": True},
{"id": 104, "name": "Monitor Arm", "price": 30.00, "in_stock": True},
{"id": 105, "name": "USB Hub", "price": 12.50, "in_stock": False},
]
# 1. Filter: Get only products that are in stock
available_products = [p for p in products if p["in_stock"]]
print("Available Products:", available_products)
# 2. Transform: Get names of products under $50
affordable_product_names = [p["name"] for p in products if p["price"] < 50.00]
print("Affordable Product Names:", affordable_product_names)
# 3. Filter and Transform: Create a list of tuples (id, name) for available products priced under $40
filtered_transformed_data = [(p["id"], p["name"]) for p in products if p["in_stock"] and p["price"] < 40.00]
print("Filtered & Transformed Data:", filtered_transformed_data)
How it works: This snippet showcases the power of Python list comprehensions for performing filtering and transformation operations on lists of dictionaries. List comprehensions provide a concise and readable way to create new lists based on existing ones. They are highly efficient and commonly used in web development for processing data retrieved from databases or external APIs, preparing it for display, further processing, or sending as API responses.