
Comprehensions are one of Python's most powerful features. Here's how pros use them.
Flatten a nested list:
nested = [[1, 2], [3, 4], [5, 6]] flat = [x for sublist in nested for x in sublist] # [1, 2, 3, 4, 5, 6]
Invert a dictionary:
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
# {1: "a", 2: "b", 3: "c"}Group words by length:
words = ["cat", "dog", "elephant", "ox", "bee"]
grouped = {length: [w for w in words if len(w) == length]
for length in set(len(w) for w in words)}
# {3: ["cat", "dog", "bee"], 8: ["elephant"], 2: ["ox"]}Extract emails from user list:
users = [{"name": "Alice", "email": "[email protected]", "active": True},
{"name": "Bob", "email": "[email protected]", "active": False}]
active_emails = [u["email"] for u in users if u["active"]]Reference:
TaskLoco™ — The Sticky Note GOAT