PYTHON

Transform and Filter Data with List Comprehensions

Master Python list comprehensions to concisely filter and transform lists of dictionaries or objects, improving code readability and performance for web data processing tasks.

# Example data: a list of product dictionaries
products = [
    {"id": 1, "name": "Laptop", "price": 1200, "in_stock": True},
    {"id": 2, "name": "Mouse", "price": 25, "in_stock": True},
    {"id": 3, "name": "Keyboard", "price": 75, "in_stock": False},
    {"id": 4, "name": "Monitor", "price": 300, "in_stock": True},
    {"id": 5, "name": "Webcam", "price": 50, "in_stock": False},
]

# --- 1. Filtering with List Comprehension ---
# Get only products that are in stock
available_products = [p for p in products if p["in_stock"]]
print(f"Available products: {available_products}")
# Expected: [{'id': 1, 'name': 'Laptop', 'price': 1200, 'in_stock': True}, ...]

# Get products cheaper than $100
cheap_products = [p for p in products if p["price"] < 100 and p["in_stock"]]
print(f"Cheap and available products: {cheap_products}")
# Expected: [{'id': 2, 'name': 'Mouse', 'price': 25, 'in_stock': True}, {'id': 5, 'name': 'Webcam', 'price': 50, 'in_stock': False}] (if webcam was in stock)

# --- 2. Transforming with List Comprehension ---
# Get only the names of available products
available_product_names = [p["name"] for p in products if p["in_stock"]]
print(f"Names of available products: {available_product_names}")
# Expected: ['Laptop', 'Mouse', 'Monitor']

# Create a new list of dictionaries with only 'id' and 'name' for all products
product_summary = [{
    "product_id": p["id"],
    "product_name": p["name"]
} for p in products]
print(f"Product summary: {product_summary}")
# Expected: [{'product_id': 1, 'product_name': 'Laptop'}, ...]

# --- 3. Combining Filter and Transform ---
# Get names of products that are in stock and cost less than $500
filtered_transformed = [
    p["name"].upper() for p in products
    if p["in_stock"] and p["price"] < 500
]
print(f"Filtered and transformed: {filtered_transformed}")
# Expected: ['MOUSE', 'MONITOR']
How it works: List comprehensions offer a concise and efficient way to create new lists from existing ones, often replacing traditional `for` loops with `append()` calls. They support both filtering elements based on a condition (`if` clause) and transforming elements into a new form. This powerful feature is invaluable for web development, allowing developers to process API responses, database query results, or user input data with remarkable clarity and often better performance than explicit loops, especially when dealing with lists of dictionaries or objects.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs