Learn Lambda Functions

A shared folder with AI prompts and code snippets

From workspace: FreeCodeCamp

Team: Main

Total snippets: 5

FreeCodeCamp

Learn Lambda Functions

5 snippets

Sort Expenses Descending Using Lambda Key

Sort expenses in descending order using lambda as the sorting key.

expenses = [10, 250, 75, 19] sorted_expenses = sorted(expenses, key=lambda x: -x) print(sorted_expenses) # Output: [250, 75, 19, 10]

Label Each Expense as Low or High

Use lambda with map and conditional expression to tag each expense.

expenses = [120.50, 32.00, 5.75, 50.00] labels = list(map(lambda x: "High" if x > 50 else "Low", expenses)) print(labels) # Output: ['High', 'Low', 'Low', 'Low']

Total Expenses Using Lambda and Reduce

Calculate the total cost using reduce and a lambda expression.

from functools import reduce expenses = [120.50, 32.00, 5.75, 50.00] total = reduce(lambda x, y: x + y, expenses) print(total) # Output: 208.25

Apply Tax to All Expenses Using Lambda and Map

Add 21% tax to each expense using a lambda inside a map function.

expenses = [100, 40, 10] with_tax = list(map(lambda x: round(x * 1.21, 2), expenses)) print(with_tax) # Output: [121.0, 48.4, 12.1]

Filter High Expenses Using Lambda and Filter

Use a lambda function to filter all expenses greater than a threshold (e.g. 50).

expenses = [120.50, 32.00, 5.75, 50.00, 89.99] high = list(filter(lambda x: x > 50, expenses)) print(high) # Output: [120.5, 89.99]