pythonintermediate10 minutes

Refactor and Improve Readability of a Data Filtering Function

Refactor a given Python function that filters and processes a list of dictionaries to improve its code quality, readability, and maintainability without altering its output behavior.

Challenge prompt

You are given a Python function that takes a list of user dictionaries and filters out those who are inactive or under 18, then returns a new list containing usernames in uppercase. The function works correctly but is hard to read and maintain. Refactor the function to improve its readability, logic clarity, and structure without changing the functionality or output.

Guidance

  • Break complex statements into smaller, descriptive helper functions if appropriate.
  • Use list comprehensions or built-in functions for filtering and mapping clearly.
  • Add meaningful variable names and remove redundant code or checks.

Hints

  • Consider combining filtering criteria into one step using list comprehensions.
  • Avoid mutating input data; work with copies or create new objects if needed.
  • Use built-in functions like map or filter for clearer intent.

Starter code

def process_users(users):
    result = []
    for u in users:
        if u['active'] == True:
            if u['age'] >=18:
                result.append(u['username'].upper())
    return result

Expected output

['ALICE', 'CHARLIE']

Core concepts

code refactoringlist comprehensionsconditional filteringstring manipulation

Challenge a Friend

Send this duel to someone else and see if they can solve it.