Map, Filter, and Reduce Functions
Lambda functions used as sort keys provide a temporary comparison value for each element without modifying the original list.
A Temporary Value Controls Order
Two ideas drive this lesson. A lambda function can temporarily convert each list element into a comparison value for sorting. A list comprehension can transform selected elements from an existing list into a new list. In both cases, the most reliable method is to trace what happens to each element rather than guessing from the compact syntax.
What do you think happens?
A list contains two points: the point with x-coordinate 2 followed by the point with x-coordinate 4. If the sort key returns each point's x-coordinate, what happens to the order?
Reveal answer
Answer: The points stay in that order because 2 is less than 4.
The lambda returns comparison values, not replacement elements. The sorting operation uses those values to determine order, while the original point elements remain in their original form.
Sorting Through a Lambda Key
A lambda function is a small, unnamed function written inline. When it is supplied to the sort method's key parameter, the lambda receives each element one at a time and returns a value. That returned value becomes the basis for sorting. The elements themselves are not changed into those returned values. For example, when the elements are point dictionaries, a lambda can return p['x'], so the x-coordinate controls the order while each complete point remains an element in the result.
Sorting Points by Their X-Coordinates
A list contains two point dictionaries. The first point has x-coordinate 2, and the second has x-coordinate 4. A sort key returns each point's x-coordinate.
Inspect the first point: The lambda receives the first point and returns 2.
Inspect the second point: The lambda receives the second point and returns 4.
Compare the returned values: The sorting operation compares 2 and 4. Since 2 is less than 4, the existing order already matches the ascending comparison order.
Keep the elements: The result contains the original point elements, not a list containing only the numbers 2 and 4.
The points remain in their original order, and the original point data stays intact.
A sort key changes the logic used to compare elements, not the form of the elements being sorted. If the points begin in reverse order, the same x-coordinate key causes them to be reordered.
Building Lists with Comprehensions
A list comprehension is compact syntax for creating a new list from an existing iterable. Its general structure is [expression for item in list if condition]. Read it as: take each item from the source list, optionally check a condition, calculate the expression for items that pass, and collect those results into a new list.
Doubling Every Source Number
Apply the list comprehension [i * 2 for i in [2, 3, 4]].
Take 2: The expression multiplies 2 by 2, producing 4.
Take 3: The expression multiplies 3 by 2, producing 6.
Take 4: The expression multiplies 4 by 2, producing 8.
Collect the results: The calculated values are placed into a new list in the source traversal order.
The source list is [2, 3, 4], and the new list is [4, 6, 8].
A comprehension always creates a new list. When a condition is included, that condition is checked for each source element, and only elements that pass are transformed and included.
Different Jobs, Related Tools
| Feature | What it does | What happens to the elements |
|---|---|---|
| Lambda used as a sort key | Returns a temporary comparison value for each element | The original elements stay in their original form while their order is determined |
| List comprehension | Transforms source elements and can optionally filter them | The transformed results are collected into a new list |
A lambda is a function: it accepts an input and returns an output. By itself, it does not create a new list. A list comprehension is a list-building expression: it visits source elements, applies an expression, optionally filters elements, and collects the results. This is why lambda functions are often useful for sorting and filtering operations, while comprehensions are useful when the goal is to construct a new list.
Tracing a More Useful Sort Key
A lambda sort key does not have to extract one existing field. The source material describes a list of points in two-dimensional space, where each point has x and y coordinates. A lambda can compute a derived value, such as distance from the origin at 0, 0, and the sorting operation can use that value to order the points.
Sorting by Distance from the Origin
Sort points by their distance from the origin. The distance is calculated from the x and y coordinates using the square root of x squared plus y squared.
Receive one point: The lambda receives a point dictionary containing an x coordinate and a y coordinate.
Compute its comparison value: The lambda calculates the point's distance from the origin using its coordinates.
Repeat for every point: Each point receives its own temporary distance value.
Use the values for order: The sorting operation compares the calculated distances to determine the order of the complete point elements.
The points are ordered by their calculated distances, while each result element remains a point rather than becoming only a distance.
When predicting a lambda-based sort, make a two-column trace: write each original element in one column and the value returned by the lambda in the other. Sort by the returned values, then report the original elements in that order. This prevents the common mistake of confusing comparison keys with replacement data.
Mistakes in Compact Syntax
Treating the lambda's returned key as the new list element.
The lambda output is used as a temporary comparison value. The original elements remain the elements being ordered.
Fix:
Use the returned key to determine order, then keep track of the complete original elements.Assuming a comprehension modifies the source list.
A list comprehension creates a new list from the source list.
Fix:
Treat the source list and the newly collected result as separate lists.Applying the expression before considering the condition.
The condition determines which elements are transformed and included.
Fix:
Trace each item through the condition first, then apply the expression only to items that pass.Putting comprehension clauses in the wrong order.
The compact syntax depends on the order of the expression, for clause, and optional if clause.
Fix:
Check the structure against [expression for item in list if condition].Overlooking lambda punctuation or structure.
The source material emphasizes careful attention to syntax, including colons and clause order.
Fix:
Check the lambda syntax carefully, then trace the input and returned value one element at a time.
When debugging either feature, expand the compact operation mentally into individual passes. For sorting, record each element and its returned key. For a comprehension, record each source item, whether it passes the condition, and the transformed value that is added. This separates syntax problems from logic problems.
Guided Practice
Predict the result of sorting two point dictionaries by a lambda key that returns each point's x-coordinate. Then trace the comprehension [i * 2 for i in [2, 3, 4]] item by item. Finally, explain what the condition in a comprehension controls when one is added.
Hints
- For sorting, list the value returned by the lambda for every point.
- For the comprehension, calculate the expression separately for 2, 3, and 4.
- A condition determines which source elements are transformed and included.
- Keep the original elements separate from the temporary comparison values.
What do you think happens?
What list is produced by [i * 2 for i in [2, 3, 4]]?
Reveal answer
Answer: [4, 6, 8]
The comprehension takes each source item, multiplies it by 2, and collects the three transformed values into a new list.
Key Takeaways
- A lambda used as a sort key receives elements one at a time and returns temporary comparison values. Those values determine order, while the original elements retain their form. A list comprehension creates a new list by applying an expression to source elements. Its optional condition controls which elements are transformed and included. To predict or debug either operation, trace every element and record the intermediate value before deciding the final result.
Key Takeaways
- A lambda sort key transforms each element into a temporary value used for comparison.
- Sorting uses the lambda's returned values without replacing the original elements.
- List comprehensions create new lists by transforming source elements.
- An optional comprehension condition controls which elements are transformed and included.
- Step-by-step tracing helps predict results and debug compact syntax.