ProgrammingHardCognizant GenC · TCS NQT

What is printed?

What is printed?
people = [('Ann', 30), ('Bob', 25), ('Cid', 30), ('Dan', 25)]
s1 = sorted(people, key=lambda p: p[0])
s2 = sorted(s1, key=lambda p: p[1], reverse=True)
print([p[0] for p in s2])
  1. A. ['Cid', 'Ann', 'Dan', 'Bob']
  2. B. ['Ann', 'Bob', 'Cid', 'Dan']
  3. C. ['Ann', 'Cid', 'Dan', 'Bob']
  4. D. ['Ann', 'Cid', 'Bob', 'Dan']

Correct answer: D. ['Ann', 'Cid', 'Bob', 'Dan']

The first pass sorts by name and the second sorts by age descending. Sorting is stable, so people with equal ages keep their name order: Ann before Cid, and Bob before Dan.

More Python Programming questions

Exams that ask this topic