PYTHON

Efficient Data Transformation with List Comprehensions

Transform and filter data concisely and efficiently in Python by creating new lists using powerful list comprehensions, enhancing readability and performance.

# Original list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 1. Filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
print(f"Even numbers: {even_numbers}")

# 2. Square each number
squared_numbers = [num ** 2 for num in numbers]
print(f"Squared numbers: {squared_numbers}")

# 3. Filter and transform (square only even numbers)
squared_even_numbers = [num ** 2 for num in numbers if num % 2 == 0]
print(f"Squared even numbers: {squared_even_numbers}")

# 4. Process a list of dictionaries (e.g., extract names from users)
users = [
    {'id': 1, 'name': 'Alice', 'active': True},
    {'id': 2, 'name': 'Bob', 'active': False},
    {'id': 3, 'name': 'Charlie', 'active': True},
]
active_user_names = [user['name'] for user in users if user['active']]
print(f"Active user names: {active_user_names}")
How it works: List comprehensions offer a concise and readable way to create new lists based on existing iterables. They consist of an expression followed by a `for` clause, and optionally one or more `if` or `for` clauses. This allows for powerful filtering (with `if` conditions) and transformation (applying an expression to each item) of data in a single line, often resulting in more efficient and elegant code compared to traditional `for` loops.

Need help integrating this into your project?

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

Hire DigitalCodeLabs