PYTHON
Efficient Data Filtering and Transformation with List Comprehensions
Master Python list comprehensions to concisely filter and transform data, creating new lists based on conditions and expressions in a single line.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
users = [
{'name': 'Alice', 'active': True, 'level': 5},
{'name': 'Bob', 'active': False, 'level': 3},
{'name': 'Charlie', 'active': True, 'level': 8},
]
# Filter for even numbers and square them
squared_evens = [n**2 for n in numbers if n % 2 == 0]
print(f"Squared Evens: {squared_evens}")
# Extract names of active users with a higher level
high_level_active_users = [
user['name'] for user in users
if user['active'] and user['level'] > 4
]
print(f"High Level Active Users: {high_level_active_users}")
# Expected output:
# Squared Evens: [4, 16, 36, 64, 100]
# High Level Active Users: ['Alice', 'Charlie']
How it works: List comprehensions provide a concise way to create new lists from existing iterables. They combine filtering (`if` clause) and transformation (expression before `for`) into a single, readable line, often replacing multi-line loops.