ProgrammingVery hardProduct-company MCQ pattern

What is printed on the second line?

What is printed on the second line?
data = [('b', 2), ('a', 2), ('c', 1), ('a', 1)]
print(sorted(data, key=lambda t: (t[1], t[0]), reverse=True))
print(sorted(sorted(data, key=lambda t: t[0]), key=lambda t: t[1], reverse=True))
  1. A. [('a', 2), ('b', 2), ('c', 1), ('a', 1)]
  2. B. [('b', 2), ('a', 2), ('a', 1), ('c', 1)]
  3. C. [('a', 2), ('b', 2), ('a', 1), ('c', 1)]
  4. D. [('a', 1), ('c', 1), ('a', 2), ('b', 2)]

Correct answer: C. [('a', 2), ('b', 2), ('a', 1), ('c', 1)]

Sorting by name first and then stably by the number (descending) keeps names in alphabetical order inside each number group. Two stable sorts give the same result as one sort on a tuple key.

More Python Programming questions

Exams that ask this topic