BudiBadu Logo

Sort Items by Custom Criteria

Python Medium 1 views

Learn Python lambda functions to write concise, inline operations for sorting, filtering, and transforming data. Lambda functions are anonymous functions perfect for short operations passed as arguments to higher-order functions.

You will use lambdas with built-in functions like sorted, filter, and map to process data efficiently. The key is knowing when to use lambdas versus regular functions for maximum code clarity.

Example 1:

Input: numbers = [3, 1, 4, 1, 5, 9, 2]
Output: [1, 1, 2, 3, 4, 5, 9]
Explanation: Sort numbers in ascending order using sorted() with default comparison.

Example 2:

Input: words = ["apple", "pie", "a", "be"]
Output: ["a", "be", "pie", "apple"]
Explanation: Sort by length using lambda as key function.

Example 3:

Input: numbers = [1, 2, 3, 4, 5, 6]
Output: [2, 4, 6]
Explanation: Filter even numbers using lambda predicate.

Algorithm Flow

Recommendation Algorithm Flow for Sort Items by Custom Criteria - Budibadu
Recommendation Algorithm Flow for Sort Items by Custom Criteria - Budibadu

Best Answers

python - Approach 1
def sort_and_filter(items):
    get_value = lambda x: x[1]
    return sorted(items, key=get_value)