PYTHON

Efficient List Transformation and Filtering with List Comprehensions

Learn to use Python's list comprehensions for concise and efficient creation of new lists by transforming or filtering elements from existing iterables, enhancing code readability.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Transform: Square all numbers
squared_numbers = [x * x for x in numbers]
print(f"Squared numbers: {squared_numbers}")

# Filter: Get only even numbers
even_numbers = [x for x in numbers if x % 2 == 0]
print(f"Even numbers: {even_numbers}")

# Transform and Filter: Square only even numbers
squared_even_numbers = [x * x for x in numbers if x % 2 == 0]
print(f"Squared even numbers: {squared_even_numbers}")

# Using list comprehension with a dictionary (items)
products = [
    {"name": "Laptop", "price": 1200},
    {"name": "Mouse", "price": 25},
    {"name": "Keyboard", "price": 75}
]
expensive_products = [p["name"] for p in products if p["price"] > 50]
print(f"Expensive products (names): {expensive_products}")
How it works: List comprehensions offer a compact and highly readable way to create new lists. They streamline operations like transforming each item in a list (e.g., squaring numbers), filtering items based on a condition (e.g., selecting even numbers), or performing both transformation and filtering simultaneously. This approach is often more Pythonic and can be more performant than traditional loops for these tasks, especially when dealing with large datasets or complex iterables like lists of dictionaries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs