DEV Community

Alex Chen
Alex Chen

Posted on

Quick Tip: Python List Comprehensions That Replace 6 Lines of Loop

Stop writing 6 lines of loop for something Python does in one.

Quick Tip

Filtering + transforming a list in one expression:

# ❌ The loop way
active_names = []
for user in users:
    if user.is_active:
        active_names.append(user.name.upper())

# ✅ One line
active_names = [u.name.upper() for u in users if u.is_active]
Enter fullscreen mode Exit fullscreen mode

Works with dicts and sets too:

# Dict: id -> email for admins only
admin_emails = {u.id: u.email for u in users if u.is_admin}

# Set: unique domains
domains = {u.email.split("@")[1] for u in users}
Enter fullscreen mode Exit fullscreen mode

Add a conditional value with a ternary inside:

labels = ["adult" if u.age >= 18 else "minor" for u in users]
Enter fullscreen mode Exit fullscreen mode

Nested flattening:

# [[1,2],[3,4]] -> [1,2,3,4]
flat = [x for row in matrix for x in row]
Enter fullscreen mode Exit fullscreen mode

When NOT to use it: if your comprehension needs more than one condition plus a ternary, or spans two lines — write the loop. Readability beats cleverness. A comprehension nobody can parse in 3 seconds is technical debt, not style.

Benchmark on 1M items: comprehension is ~20% faster than the equivalent append loop (CPython builds the list without method-call overhead). Free performance for cleaner code.

What's your favorite one-liner that confuses every new dev on your team?


Powered by MonkeyCode — free AI coding assistant that suggests these refactors automatically: https://ly.cyberserval.tech/iIETXiF

Top comments (0)