Back to Freecodecamp

Step 30

curriculum/challenges/english/blocks/learn-lambda-functions-by-building-an-expense-tracker/65824111a09164518320088d.md

latest2.1 KB
Original Source

--description--

The filter() function allows you to select items from an iterable, such as a list, based on the output of a function:

py
filter(my_function, my_list)

filter() takes a function as its first argument and an iterable as its second argument. It returns an iterator, which is a special object that enables you to iterate over the elements of a collection, like a list.

The result of the example above is an iterator containing the elements of my_list for which my_function returns True.

Within the filter_expenses_by_category function, call filter() passing the lambda function you wrote in the previous step as the first argument and the expenses list as the second argument.

--hints--

You should call filter() inside the filter_expenses_by_category function.

js
({ test: () => assert(runPython(`len(_Node(_code).find_function("filter_expenses_by_category").find_calls("filter")) == 1`)) })

You should pass lambda expense: expense['category'] == category as the first argument to the filter() call.

js
({ test: () => assert(runPython(`_Node(_code).find_function("filter_expenses_by_category").find_calls("filter")[0].find_call_args()[0].is_equivalent("lambda expense: expense['category'] == category")`)) })

You should pass expenses as the second argument to the filter() call.

js
({ test: () => assert(runPython(`_Node(_code).find_function("filter_expenses_by_category").find_calls("filter")[0].find_call_args()[1].is_equivalent("expenses")`)) })

--seed--

--seed-contents--

py
def add_expense(expenses, amount, category):
    expenses.append({'amount': amount, 'category': category})
    
def print_expenses(expenses):
    for expense in expenses:
        print(f'Amount: {expense["amount"]}, Category: {expense["category"]}')
    
def total_expenses(expenses):
    return sum(map(lambda expense: expense['amount'], expenses))
    
--fcc-editable-region--
def filter_expenses_by_category(expenses, category):
    lambda expense: expense['category'] == category
--fcc-editable-region--

expenses = []