ProgrammingHardGATE CS · Product-company placement

What is printed?

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

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

Python's sort is stable: items with equal keys keep their original relative order, so ('c', 1) stays before ('a', 1). Sorting tuples compares element by element, making ('a', 1) smallest.

More Python Programming questions

Exams that ask this topic