EasyPython

Avoid Side Effects

PythonClean CodePure FunctionsRefactoring

The function below mutates its input list — a classic source of bugs.

# dirty — mutates the original list!
def solve(cart, item):
    cart.append(item)
    cart.sort(key=lambda x: x['price'])
    return cart

Refactor `solve(cart, item)` so it returns a new sorted list without modifying cart.

After calling solve(cart, item), the original cart list must be unchanged.

Sample tests

Test #1Returns new sorted list with item added
Input: [[{"name":"B","price":20},{"name":"A","price":10}],{"name":"C","price":5}]
Output: [{"name":"C","price":5},{"name":"A","price":10},{"name":"B","price":20}]
Test #2Works with empty cart
Input: [[],{"name":"Solo","price":99}]
Output: [{"name":"Solo","price":99}]
Test #3Equal prices preserve relative order (stable sort)
Input: [[{"name":"X","price":50}],{"name":"Y","price":50}]
Output: [{"name":"X","price":50},{"name":"Y","price":50}]