Challenge - 5 Problems
Sorted Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
What is the output of sorting a list of tuples by the second element?
Consider the following Python code that sorts a list of tuples by the second item in each tuple.
Python
data = [(3, 4), (1, 2), (5, 1)] sorted_data = sorted(data, key=lambda x: x[1]) print(sorted_data)
Attempts:
2 left
๐ก Hint
Look at the second element of each tuple and sort by that.
โ Incorrect
The sorted() function sorts the list by the key function, which here returns the second element of each tuple. So the tuples are ordered by 1, 2, then 4.
โ Predict Output
intermediate2:00remaining
What is the output when sorting a string with sorted()?
What will be printed by this code?
Python
result = sorted('banana') print(result)
Attempts:
2 left
๐ก Hint
sorted() returns a list of characters sorted alphabetically.
โ Incorrect
The string 'banana' is split into characters and sorted alphabetically, resulting in three 'a's, one 'b', and two 'n's in order.
โ Predict Output
advanced2:00remaining
What is the output of sorting a dictionary by its values?
Given this dictionary, what will be the output of the sorted() call?
Python
scores = {'Alice': 88, 'Bob': 75, 'Charlie': 90}
sorted_scores = sorted(scores.items(), key=lambda item: item[1])
print(sorted_scores)Attempts:
2 left
๐ก Hint
The key function sorts by the dictionary values.
โ Incorrect
sorted() sorts the items by the second element of each tuple (the score), so the order is Bob (75), Alice (88), Charlie (90).
โ Predict Output
advanced2:00remaining
What is the output of sorting a list with reverse=True?
What will this code print?
Python
numbers = [4, 1, 7, 3] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers)
Attempts:
2 left
๐ก Hint
reverse=True sorts from largest to smallest.
โ Incorrect
The sorted() function sorts the list in descending order because reverse=True is set.
๐ง Conceptual
expert2:00remaining
Which option will cause a TypeError when used with sorted()?
Which of these options will cause a TypeError when passed as the key argument to sorted()?
Attempts:
2 left
๐ก Hint
The key argument must be a function, not a number.
โ Incorrect
Passing an integer (5) as the key argument causes a TypeError because sorted() expects a callable function for key.