PYTHON
Advanced List Comprehensions for Complex Data Transformations
Master Python's list comprehensions for concise and efficient filtering, mapping, and transforming of data. Enhance code readability and performance when working with lists.
data = [
{'name': 'Alice', 'score': 85, 'active': True},
{'name': 'Bob', 'score': 92, 'active': False},
{'name': 'Charlie', 'score': 78, 'active': True},
{'name': 'David', 'score': 95, 'active': True},
{'name': 'Eve', 'score': 60, 'active': False}
]
# 1. Filter and transform: Get names of active users with score > 80
active_high_scorers = [
user['name'] for user in data
if user['active'] and user['score'] > 80
]
print(f"Active high scorers: {active_high_scorers}")
# 2. Nested list comprehension: Flatten a list of lists and convert to uppercase
list_of_lists = [['a', 'b'], ['c', 'd', 'e']]
flattened_uppercase = [
item.upper() for sublist in list_of_lists for item in sublist
]
print(f"Flattened and uppercase: {flattened_uppercase}")
# 3. Conditional transformation: Assign grades based on score
grades = [
f"{user['name']}: {'Pass' if user['score'] >= 70 else 'Fail'}"
for user in data
]
print(f"Grades: {grades}")
How it works: List comprehensions offer a Pythonic and compact way to create new lists. This snippet demonstrates advanced usage including filtering elements based on multiple conditions, transforming elements conditionally, and even flattening nested lists. They improve code readability and often provide better performance compared to traditional `for` loops with append operations, making them essential for efficient data manipulation.