← Back to all snippets
PYTHON

Transform and Filter Lists with Python List Comprehensions

Master Python list comprehensions to efficiently filter elements and apply transformations, creating new lists based on existing data structures for clean and concise code.

data = [
    {'id': 1, 'name': 'Item A', 'price': 100, 'active': True},
    {'id': 2, 'name': 'Item B', 'price': 250, 'active': False},
    {'id': 3, 'name': 'Item C', 'price': 50, 'active': True},
    {'id': 4, 'name': 'Item D', 'price': 180, 'active': True}
]

# 1. Filter active items
active_items = [item for item in data if item['active']]
print(f"Active Items: {active_items}")

# 2. Transform: Get names of items with price > 150
high_price_names = [item['name'] for item in data if item['price'] > 150]
print(f"High Price Names: {high_price_names}")

# 3. Filter and transform: Get IDs of active items with price < 200
filtered_ids = [item['id'] for item in data if item['active'] and item['price'] < 200]
print(f"Filtered IDs: {filtered_ids}")
How it works: List comprehensions offer a concise way to create lists based on existing iterables. They combine filtering (`if` clause) and transformation (`expression` before `for`) into a single line. This significantly improves readability and often performance compared to traditional `for` loops with `append` and `if` statements. This technique is invaluable for processing data fetched from databases or APIs in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs