Lambda with sorted() in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use sorted() with a lambda function, we want to know how the sorting time changes as the list grows.
We ask: How does the work needed to sort change when the list gets bigger?
Analyze the time complexity of the following code snippet.
numbers = [(1, 3), (3, 2), (5, 1), (2, 4)]
sorted_numbers = sorted(numbers, key=lambda x: x[1])
print(sorted_numbers)
This code sorts a list of pairs by the second number in each pair using a lambda function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing elements using the lambda key function during sorting.
- How many times: The sorting algorithm compares elements multiple times, depending on the list size.
As the list gets bigger, the number of comparisons grows faster than the list size itself.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 comparisons |
| 100 | About 700 comparisons |
| 1000 | About 10,000 comparisons |
Pattern observation: The work grows faster than the list size, roughly like the list size times its logarithm.
Time Complexity: O(n log n)
This means sorting takes more time as the list grows, but not as fast as checking every pair with every other pair.
[X] Wrong: "Using a lambda makes sorting slower by a lot because it adds extra work for each comparison."
[OK] Correct: The lambda function runs once per element to compute keys, not once per comparison, so the main time is still spent in sorting steps, and the overall growth stays the same.
Understanding how sorting with a custom key works helps you explain how your code handles data efficiently, a useful skill in many coding tasks.
"What if we replaced the lambda with a precomputed list of keys? How would the time complexity change?"
Practice
key argument do when used with sorted() and a lambda function in Python?Solution
Step 1: Understand the role of
Thekeyinsorted()keyargument takes a function that extracts a value from each item to use for sorting.Step 2: Understand how
Thelambdaworks withkeylambdafunction defines this extraction rule inline, tellingsorted()what to compare.Final Answer:
It tellssorted()how to compare items by extracting a value from each item. -> Option CQuick Check:
key=lambda x: valuemeans compare by value [OK]
- Thinking key changes the original list
- Confusing key with reverse sorting
- Assuming lambda filters items
data = [(2, 'b'), (1, 'a'), (3, 'c')] by the first element using sorted() and a lambda?Solution
Step 1: Identify the correct use of
Thekeyargumentkeyargument must be named and assigned a function, here a lambda.Step 2: Check lambda syntax and index
lambda x: x[0]correctly extracts the first element of each tuple for sorting.Final Answer:
sorted(data, key=lambda x: x[0]) -> Option AQuick Check:
Correct syntax uses key= and lambda with index [OK]
- Omitting key= argument name
- Using wrong tuple index
- Passing lambda as second positional argument
data = ['apple', 'banana', 'cherry'] sorted_list = sorted(data, key=lambda x: len(x)) print(sorted_list)
Solution
Step 1: Understand sorting by length
The lambda extracts the length of each string: apple(5), banana(6), cherry(6).Step 2: Sort strings by their length
Sorted order by length is: apple(5), banana(6), cherry(6). Since banana and cherry have same length, original order among them is preserved (banana before cherry).Final Answer:
['apple', 'banana', 'cherry'] -> Option AQuick Check:
Sort by len(x) = ['apple', 'banana', 'cherry'] [OK]
- Assuming alphabetical sort instead of length
- Mixing order of equal length items
- Forgetting sorted returns new list
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
sorted_data = sorted(data, key=lambda x: x['age'])
print(sorted_data)Solution
Step 1: Check dictionary keys and lambda syntax
Each dictionary has the key 'age', and lambda accesses it correctly with single quotes.Step 2: Confirm sorted() usage on list of dicts
sorted() can sort list of dictionaries using key function; no error occurs.Final Answer:
There is no error; the code sorts by age correctly. -> Option BQuick Check:
Access dict keys with quotes; sorted works on list of dicts [OK]
- Thinking single quotes cause error
- Assuming KeyError without missing keys
- Believing sorted() can't handle dicts
products = [('pen', 1.5), ('notebook', 2.0), ('eraser', 0.5), ('pencil', 1.5)]How would you sort this list first by price ascending, then by product name alphabetically using sorted() and lambda?Solution
Step 1: Understand sorting by multiple criteria
To sort by price then name, use a tuple in key: (price, name).Step 2: Write lambda returning tuple for sorting
lambda x: (x[1], x[0])returns price first, then product name.Final Answer:
sorted(products, key=lambda x: (x[1], x[0])) -> Option DQuick Check:
Use tuple in key=lambda for multi-level sort [OK]
- Using logical operators instead of tuple
- Passing multiple key arguments
- Reversing order of sort keys
