ProgrammingHardProduct-company MCQ pattern

What is printed?

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

Correct answer: A. [(2, 'b'), (2, 'a'), (1, 'z'), (1, 'y')]

Both sorts are stable, and reverse=True keeps the original order of equal keys rather than reversing them. The second line therefore lists the key-2 items in input order (b, a) and then the key-1 items in input order (z, y).

More Python Programming questions

Exams that ask this topic