← Back to all snippets
PYTHON

Filtering and Mapping Lists with Comprehensions

Use Python list comprehensions for concise filtering and transformation of list elements, streamlining data processing and preparation for web applications.

# Example 1: Filtering a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
# even_numbers will be [2, 4, 6, 8, 10]

# Example 2: Mapping values (transforming each item)
words = ["hello", "world", "python", "web"]
uppercase_words = [word.upper() for word in words]
# uppercase_words will be ['HELLO', 'WORLD', 'PYTHON', 'WEB']

# Example 3: Combining filtering and mapping
products = [
    {"name": "Laptop", "price": 1200, "in_stock": True},
    {"name": "Mouse", "price": 25, "in_stock": False},
    {"name": "Keyboard", "price": 75, "in_stock": True},
]
available_product_names = [p["name"] for p in products if p["in_stock"]]
# available_product_names will be ['Laptop', 'Keyboard']
How it works: List comprehensions offer a succinct syntax to create new lists based on existing iterables. They can be used to filter elements (by including an `if` clause) or to transform elements (by applying an expression to each item), or both. This method significantly improves code readability and performance compared to traditional `for` loops with `append()`, making it a go-to for data manipulation, cleaning, and preparation tasks 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