ProgrammingVery hardTCS NQT · Accenture

What is printed?

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

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

The first sort orders by name, and sorted is stable, so later sorts keep that order for ties. Sorting by the number in reverse keeps ties in their existing order: a before b for value 2, and a before c for value 1.

More Python Programming questions

Exams that ask this topic