Python

Lesson 04

List and dict comprehensions

Use comprehensions for clear transformations, but switch to loops when branching becomes the main story.

Good Code

reviewers.py
def active_reviewer_emails(users):
    return [
        user.email.lower()
        for user in users
        if user.is_active and user.email
    ]

Bad Code

reviewers.py
def active_reviewer_emails(users):
    emails = []
    for user in users:
        if user.is_active:
            if user.email:
                emails.append(user.email.lower())
    return emails

Review Notes

What to review

Good Code

The good version expresses one filter and one transformation in a compact shape.

Bad Code

The bad version spreads a simple collection transformation across nested conditionals, making the main intent harder to see.

Takeaways

  • A comprehension should make simple filtering and mapping easier to read, not denser to parse.