ProgrammingVery hardTCS NQT · Accenture

What is printed?

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

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

Sorting by the first element only keeps the original order of the two 1s, giving b before a. Sorting whole tuples compares the second element for ties, so a comes before b.

More Python Programming questions

Exams that ask this topic