Bird
Raised Fist0
Pythonprogramming~20 mins

Lambda with sorted() in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
๐ŸŽ–๏ธ
Lambda Sorting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Sorting a list of tuples by second element using lambda
What is the output of this code?
data = [(3, 2), (1, 5), (4, 1)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
Python
data = [(3, 2), (1, 5), (4, 1)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
A[(1, 5), (3, 2), (4, 1)]
B[(4, 1), (3, 2), (1, 5)]
C[(3, 2), (4, 1), (1, 5)]
D[(4, 1), (1, 5), (3, 2)]
Attempts:
2 left
๐Ÿ’ก Hint
Look at the second element of each tuple and how sorted() uses the lambda key.
โ“ Predict Output
intermediate
2:00remaining
Sorting strings by length using lambda
What is the output of this code?
words = ['apple', 'banana', 'fig', 'date']
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)
Python
words = ['apple', 'banana', 'fig', 'date']
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)
A['fig', 'date', 'apple', 'banana']
B['banana', 'apple', 'date', 'fig']
C['apple', 'banana', 'date', 'fig']
D['date', 'fig', 'apple', 'banana']
Attempts:
2 left
๐Ÿ’ก Hint
Check the length of each word and how sorted() orders them.
โ“ Predict Output
advanced
2:30remaining
Sorting a list of dictionaries by nested key using lambda
What is the output of this code?
items = [{'name': 'apple', 'info': {'price': 5}}, {'name': 'banana', 'info': {'price': 3}}, {'name': 'cherry', 'info': {'price': 7}}]
sorted_items = sorted(items, key=lambda x: x['info']['price'])
print([item['name'] for item in sorted_items])
Python
items = [{'name': 'apple', 'info': {'price': 5}}, {'name': 'banana', 'info': {'price': 3}}, {'name': 'cherry', 'info': {'price': 7}}]
sorted_items = sorted(items, key=lambda x: x['info']['price'])
print([item['name'] for item in sorted_items])
A['apple', 'banana', 'cherry']
B['cherry', 'apple', 'banana']
C['banana', 'apple', 'cherry']
D['banana', 'cherry', 'apple']
Attempts:
2 left
๐Ÿ’ก Hint
Look inside the nested dictionary to find the price for sorting.
โ“ Predict Output
advanced
2:00remaining
Sorting with lambda and reverse order
What is the output of this code?
numbers = [10, 3, 7, 1]
sorted_numbers = sorted(numbers, key=lambda x: -x)
print(sorted_numbers)
Python
numbers = [10, 3, 7, 1]
sorted_numbers = sorted(numbers, key=lambda x: -x)
print(sorted_numbers)
A[1, 3, 7, 10]
B[10, 3, 7, 1]
C]01 ,7 ,3 ,1[
D[10, 7, 3, 1]
Attempts:
2 left
๐Ÿ’ก Hint
The lambda negates each number, so sorting by negative values reverses order.
๐Ÿง  Conceptual
expert
3:00remaining
Understanding lambda with sorted() behavior on complex keys
Given the code below, what is the output?
data = ['a1', 'a10', 'a2', 'a11']
sorted_data = sorted(data, key=lambda x: (x[0], int(x[1:])))
print(sorted_data)
Python
data = ['a1', 'a10', 'a2', 'a11']
sorted_data = sorted(data, key=lambda x: (x[0], int(x[1:])))
print(sorted_data)
A['a1', 'a2', 'a10', 'a11']
B['a1', 'a10', 'a11', 'a2']
C['a10', 'a11', 'a1', 'a2']
D['a11', 'a10', 'a2', 'a1']
Attempts:
2 left
๐Ÿ’ก Hint
The lambda sorts first by the letter, then by the number part as integer.

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

  1. 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.
  2. Step 2: Understand how lambda works with key

    The lambda function defines this extraction rule inline, telling sorted() what to compare.
  3. Final Answer:

    It tells sorted() how to compare items by extracting a value from each item. -> Option C
  4. 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

  1. Step 1: Identify the correct use of key argument

    The key argument must be named and assigned a function, here a lambda.
  2. Step 2: Check lambda syntax and index

    lambda x: x[0] correctly extracts the first element of each tuple for sorting.
  3. Final Answer:

    sorted(data, key=lambda x: x[0]) -> Option A
  4. Quick Check:

    Correct syntax uses key= and lambda with index [OK]
Hint: Always use key= with lambda for sorting rules [OK]
Common Mistakes:
  • Omitting key= argument name
  • Using wrong tuple index
  • Passing lambda as second positional argument
3. What is the output of this code?
data = ['apple', 'banana', 'cherry']
sorted_list = sorted(data, key=lambda x: len(x))
print(sorted_list)
medium
A. ['apple', 'banana', 'cherry']
B. ['banana', 'cherry', 'apple']
C. ['cherry', 'banana', 'apple']
D. ['apple', 'cherry', 'banana']

Solution

  1. Step 1: Understand sorting by length

    The lambda extracts the length of each string: apple(5), banana(6), cherry(6).
  2. 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).
  3. Final Answer:

    ['apple', 'banana', 'cherry'] -> Option A
  4. Quick Check:

    Sort by len(x) = ['apple', 'banana', 'cherry'] [OK]
Hint: Sort by length with key=lambda x: len(x) [OK]
Common Mistakes:
  • Assuming alphabetical sort instead of length
  • Mixing order of equal length items
  • Forgetting sorted returns new list
4. Find the error in this code snippet:
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
sorted_data = sorted(data, key=lambda x: x['age'])
print(sorted_data)
medium
A. The code will raise a KeyError because 'age' is missing.
B. There is no error; the code sorts by age correctly.
C. The lambda function should use double quotes for keys.
D. sorted() cannot sort dictionaries.

Solution

  1. Step 1: Check dictionary keys and lambda syntax

    Each dictionary has the key 'age', and lambda accesses it correctly with single quotes.
  2. Step 2: Confirm sorted() usage on list of dicts

    sorted() can sort list of dictionaries using key function; no error occurs.
  3. Final Answer:

    There is no error; the code sorts by age correctly. -> Option B
  4. Quick Check:

    Access dict keys with quotes; sorted works on list of dicts [OK]
Hint: Dictionaries can be sorted by key with lambda [OK]
Common Mistakes:
  • Thinking single quotes cause error
  • Assuming KeyError without missing keys
  • Believing sorted() can't handle dicts
5. You have a list of tuples representing products and their prices:
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?
hard
A. sorted(products, key=lambda x: x[1] and x[0])
B. sorted(products, key=lambda x: x[1] or x[0])
C. sorted(products, key=lambda x: x[0], x[1])
D. sorted(products, key=lambda x: (x[1], x[0]))

Solution

  1. Step 1: Understand sorting by multiple criteria

    To sort by price then name, use a tuple in key: (price, name).
  2. Step 2: Write lambda returning tuple for sorting

    lambda x: (x[1], x[0]) returns price first, then product name.
  3. Final Answer:

    sorted(products, key=lambda x: (x[1], x[0])) -> Option D
  4. Quick Check:

    Use tuple in key=lambda for multi-level sort [OK]
Hint: Use tuple in lambda key for multi-level sorting [OK]
Common Mistakes:
  • Using logical operators instead of tuple
  • Passing multiple key arguments
  • Reversing order of sort keys