0
0
Pythonprogramming~10 mins

Lambda with sorted() in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lambda with sorted()
Start with list
Call sorted()
Use lambda as key
Apply lambda to each item
Compare results
Return sorted list
The sorted() function takes a list and a lambda function as a key to decide the order, then returns a new sorted list.
Execution Sample
Python
numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers, key=lambda x: -x)
print(sorted_numbers)
Sorts the list numbers in descending order using a lambda function as the key.
Execution Table
StepActionLambda Input (x)Lambda Output (-x)ComparisonSorted List State
1Apply lambda to 55-5-[5]
2Apply lambda to 22-2Compare -2 > -5[5, 2]
3Apply lambda to 99-9Compare -9 < -5 and -2[5, 2, 9]
4Apply lambda to 11-1Compare -1 > -2[5, 2, 9, 1]
5Sort by lambda output--Order by ascending lambda output[9, 5, 2, 1]
6Return sorted list---[9, 5, 2, 1]
💡 All items processed and sorted by lambda key, sorted list returned.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
numbers[5, 2, 9, 1][5, 2, 9, 1][5, 2, 9, 1][5, 2, 9, 1][5, 2, 9, 1][5, 2, 9, 1]
sorted_numbers[][][][][][9, 5, 2, 1]
Key Moments - 2 Insights
Why does the lambda use '-x' instead of just 'x'?
Using '-x' reverses the order because sorted() sorts ascending by default; the lambda output is used to compare items, so negating x sorts descending (see execution_table steps 1-5).
Does sorted() change the original list?
No, sorted() returns a new list and leaves the original list unchanged, as shown in variable_tracker where 'numbers' stays the same.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 3, what is the lambda output for input 9?
A9
B-9
C-5
D5
💡 Hint
Check the 'Lambda Output (-x)' column at Step 3 in execution_table.
At which step does the sorted list first show the item 9 at the front?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Sorted List State' column in execution_table to see when 9 moves to front.
If the lambda was changed to 'lambda x: x', how would the final sorted list change?
A[1, 2, 5, 9]
B[9, 5, 2, 1]
C[5, 2, 9, 1]
DNo change
💡 Hint
Using 'lambda x: x' sorts ascending, check variable_tracker final sorted_numbers for comparison.
Concept Snapshot
sorted(iterable, key=lambda x: ...)
- sorted() returns a new sorted list
- lambda defines sorting key for each item
- Default sort is ascending
- Use '-x' in lambda to sort descending
- Original list stays unchanged
Full Transcript
This example shows how sorted() uses a lambda function as a key to sort a list. The lambda takes each item and returns its negative, so sorted() sorts the list in descending order. The original list remains unchanged. The execution table traces each step applying the lambda and sorting. The variable tracker shows the original and sorted lists over time.