Use lambda d: d['age'] to access the 'age' value in each dictionary for sorting.
What is the output of sorted([3, 1, 2], key=lambda x: x % 2)?
A[1, 2, 3]
B[2, 3, 1]
C[3, 1, 2]
D[1, 3, 2]
✗ Incorrect
Sorting by x % 2 groups even numbers (0) before odd numbers (1), so 2 comes before 3 and 1.
Explain how to use a lambda function with sorted() to sort a list of complex items.
Think about how to tell Python what part of each item to sort by.
You got /4 concepts.
Describe a real-life example where sorting with a lambda function would be useful.
Consider sorting a list of people by age or sorting products by price.
You got /3 concepts.
Practice
(1/5)
1. What does the key argument do when used with sorted() and a lambda function in Python?
easy
A. It reverses the order of the sorted list automatically.
B. It changes the original list to a sorted list in place.
C. It tells sorted() how to compare items by extracting a value from each item.
D. It filters out items that do not match the lambda condition.
Solution
Step 1: Understand the role of key in sorted()
The key argument takes a function that extracts a value from each item to use for sorting.
Step 2: Understand how lambda works with key
The lambda function defines this extraction rule inline, telling sorted() what to compare.
Final Answer:
It tells sorted() how to compare items by extracting a value from each item. -> Option C
Quick Check:
key=lambda x: value means compare by value [OK]
Hint: Remember: key=lambda extracts sort value from each item [OK]
Common Mistakes:
Thinking key changes the original list
Confusing key with reverse sorting
Assuming lambda filters items
2. Which of the following is the correct syntax to sort a list of tuples data = [(2, 'b'), (1, 'a'), (3, 'c')] by the first element using sorted() and a lambda?
easy
A. sorted(data, key=lambda x: x[0])
B. sorted(data, lambda x: x[0])
C. sorted(data, key=lambda x: x[1])
D. sorted(data, key=x[0])
Solution
Step 1: Identify the correct use of key argument
The key argument 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 A
Quick Check:
Correct syntax uses key= and lambda with index [OK]
Hint: Always use key= with lambda for sorting rules [OK]
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 A
Quick Check:
Sort by len(x) = ['apple', 'banana', 'cherry'] [OK]
Hint: Sort by length with key=lambda x: len(x) [OK]