0
0
Pythonprogramming~20 mins

sorted() function in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Sorted Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A[(5, 1), (1, 2), (3, 4)]
B[(1, 2), (3, 4), (5, 1)]
C[(3, 4), (1, 2), (5, 1)]
D[(5, 1), (3, 4), (1, 2)]
Attempts:
2 left
๐Ÿ’ก Hint
Look at the second element of each tuple and sort by that.
โ“ Predict Output
intermediate
2:00remaining
What is the output when sorting a string with sorted()?
What will be printed by this code?
Python
result = sorted('banana')
print(result)
A['a', 'a', 'a', 'b', 'n', 'n']
B['b', 'a', 'n', 'a', 'n', 'a']
C['n', 'n', 'b', 'a', 'a', 'a']
D['a', 'b', 'n']
Attempts:
2 left
๐Ÿ’ก Hint
sorted() returns a list of characters sorted alphabetically.
โ“ Predict Output
advanced
2: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)
A[('Alice', 88), ('Bob', 75), ('Charlie', 90)]
B[('Bob', 75), ('Charlie', 90), ('Alice', 88)]
C[('Charlie', 90), ('Alice', 88), ('Bob', 75)]
D[('Bob', 75), ('Alice', 88), ('Charlie', 90)]
Attempts:
2 left
๐Ÿ’ก Hint
The key function sorts by the dictionary values.
โ“ Predict Output
advanced
2: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)
A[4, 1, 7, 3]
B[1, 3, 4, 7]
C[7, 4, 3, 1]
D[7, 3, 4, 1]
Attempts:
2 left
๐Ÿ’ก Hint
reverse=True sorts from largest to smallest.
๐Ÿง  Conceptual
expert
2: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()?
Akey=lambda x: x[0]
Bkey=5
Ckey=str.lower
Dkey=lambda x: len(x)
Attempts:
2 left
๐Ÿ’ก Hint
The key argument must be a function, not a number.