Understanding Functions and Parameters
The central distinction is purpose: a lambda supplies a function result, while a list comprehension collects transformed or filtered results into a new list.
Two Ways to Process Data
Lambda functions and list comprehensions are compact tools for working with collections. A lambda is a small, unnamed function that receives an input and returns an output. When used as a sort key, it produces a temporary comparison value for each element. A list comprehension instead creates a new list by transforming elements from a source list and, optionally, filtering them.
The central distinction is purpose: a lambda supplies a function result, while a list comprehension collects transformed or filtered results into a new list.
Sorting Through a Lambda Key
Suppose a list contains dictionaries representing points in two-dimensional space. Each point has an x coordinate and a y coordinate. A lambda can receive one point at a time and return the coordinate that should control the ordering. For example, the expression lambda p: p['x'] takes a point p and returns its x-coordinate. The sorting operation uses those returned x-values as temporary comparison values. The point dictionaries themselves remain the elements being ordered; the lambda's result determines their order.
points = [{'x': 4, 'y': 1}, {'x': 2, 'y': 3}]
points.sort(key=lambda p: p['x'])
print(points)- 1The first point produces the temporary key 4.
- 2The second point produces the temporary key 2.
- 3The sorting operation orders the points using those keys.
- 4The point data is still represented by the original dictionaries; only their order is changed in the displayed result.
- The list contains two point dictionaries.
- The lambda receives each point and returns its x-coordinate.
- The x-values are 4 and 2, so the point with x equal to 2 comes first.
- The print statement displays the resulting order.
[{'x': 2, 'y': 3}, {'x': 4, 'y': 1}]What do you think happens?
What will the sorted list contain first when the key is lambda p: p['x']?
Reveal answer
The point whose x-coordinate is 2
The lambda returns each point's x-coordinate. The comparison values are 4 and 2, and the smaller value determines the first position.
Changing the Comparison Logic
The useful part of a sort key is that it separates the data being ordered from the property used for comparison. The same points can be ordered by x-coordinate, by y-coordinate, or by a derived value such as distance from the origin. For distance from (0, 0), the source describes the formula sqrt(x^2 + y^2). A lambda can compute that value for each point and provide it as the comparison value.
[{'x': 1, 'y': 1}, {'x': 3, 'y': 4}]The first point produces a distance of 5 because sqrt(3^2 + 4^2) equals 5. The second produces sqrt(1^2 + 1^2), which is smaller than 5. The points are therefore ordered by distance rather than by either coordinate alone. The lambda's calculation changes the comparison logic without changing the fields stored in each point.
Building Lists Step by Step
A list comprehension creates a new list by taking an element from a source list, applying an expression, and collecting the result. Its general structure is [expression for item in list if condition]. The expression describes the output value, item names the current source element, list supplies the elements to visit, and the optional condition decides which elements are included.
listone = [2, 3, 4]
listtwo = [i * 2 for i in listone]
print(listtwo)- 1When i is 2, the expression produces 4.
- 2When i is 3, the expression produces 6.
- 3When i is 4, the expression produces 8.
- 4The new list preserves the sequence of the source traversal.
- The expression i * 2 describes each output value.
- The for clause visits 2, then 3, then 4.
- Each transformed value is collected in a new list.
- The resulting list is [4, 6, 8].
[4, 6, 8][2, 4]With a condition, each source element is checked before it is included. In this example, the condition keeps only values whose remainder after division by 2 is zero. Values 1, 3, and 5 fail the condition, while 2 and 4 pass and are placed in the new list.
Reading the Syntax Correctly
Common mistake Leaving out the colon in a lambda expression.
What it looks likelambda p p['x']Why it failsThe parameter and the returned expression are not separated in the required lambda structure.
Do this insteadlambda p: p['x']Common mistake Putting the comprehension clauses in the wrong order.
What it looks like[for i in numbers i * 2]Why it failsThe output expression must come before the for clause.
Do this instead[i * 2 for i in numbers]Common mistake Forgetting that a condition filters elements rather than describing the output value.
What it looks like[n for n in numbers if n % 2 == 0]Why it failsThe condition decides inclusion, while the first n supplies the value placed in the new list.
Do this insteadIdentify separately what value should be collected and which elements should pass the filter.
Common mistake Expecting a lambda used as a sort key to create a new list by itself.
What it looks likelambda p: p['x']Why it failsA lambda is a function that takes input and returns output; it does not collect results into a list by itself.
Do this insteadUse the lambda as a sort or filtering key when a comparison or selection operation needs it.
Practice Before Running
Predict both results before checking them. First, determine the order produced by sorting points with key=lambda p: p['y']. Then trace the comprehension [value + 1 for value in [2, 4, 6] if value > 2]. Write the comparison value or transformed value for every source element.
Hints
- For sorting, inspect the y-coordinate of every point and compare those temporary values.
- For the comprehension, test the condition before adding 1.
- Keep the source order when collecting the values that pass.
Tracing a Filtered Transformation
What is produced by [value + 1 for value in [2, 4, 6] if value > 2]?
- 1Check 2
The condition 2 > 2 is false, so 2 is not included.
- 2Check 4
The condition 4 > 2 is true, so the expression produces 5.
- 3Check 6
The condition 6 > 2 is true, so the expression produces 7.
[5, 7]
Key Takeaways
- 1A lambda is a small unnamed function that receives an element and returns a value.
- 2As a sort key, a lambda transforms each element into a temporary comparison value.
- 3A list comprehension creates a new list by applying an expression to source elements.
- 4An optional comprehension condition filters which elements contribute results.
- 5When debugging, check lambda colons, comprehension clause order, and the value produced for each source element.
At a glance
- Lambda sort keys determine ordering by returning a comparison value for each element.
- The original point data remains represented by its fields while the returned key controls order.
- List comprehensions transform source elements and collect the results into a new list.
- A comprehension condition filters elements before their transformed values are included.
- Tracing each element step by step is the most reliable way to predict results and find syntax or logic mistakes.