← Back to all snippets
PYTHON

Efficient List Transformation and Filtering with Comprehensions

Transform and filter lists in Python concisely using list comprehensions for clean, readable, and performant data manipulation in web applications.

# Example 1: Transform items (e.g., capitalize strings)
items = ["apple", "banana", "cherry"]
capitalized_items = [item.capitalize() for item in items]
# Result: ['Apple', 'Banana', 'Cherry']

# Example 2: Filter items (e.g., numbers greater than 5)
numbers = [1, 7, 3, 9, 2, 6]
filtered_numbers = [num for num in numbers if num > 5]
# Result: [7, 9, 6]

# Example 3: Transform and filter combined (e.g., square even numbers)
mixed_numbers = [1, 2, 3, 4, 5, 6]
squared_evens = [num * num for num in mixed_numbers if num % 2 == 0]
# Result: [4, 16, 36]

# Example 4: Dictionary comprehension for key-value transformation
price_list = {'apple': 1.0, 'banana': 0.5, 'cherry': 1.5}
discounted_prices = {item: price * 0.9 for item, price in price_list.items() if price > 1.0}
# Result: {'apple': 0.9, 'cherry': 1.35}
How it works: List and dictionary comprehensions provide a concise way to create new lists or dictionaries from existing iterables. They combine loops and conditional logic into a single line, making code more readable and often more efficient than traditional `for` loops. This snippet demonstrates transforming elements, filtering based on conditions, and combining both operations for various data manipulation needs, which is fundamental in web development for processing data from APIs or databases.

Need help integrating this into your project?

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

Hire DigitalCodeLabs