ProgrammingHardPython · GATE DA · Advanced

What is printed?

What is printed?
words = ['bb', 'a', 'cc', 'd', 'aa']
print(sorted(words, key=len, reverse=True))
print(sorted(words, key=lambda w: -len(w)))
  1. A. ['aa', 'cc', 'bb', 'd', 'a'] / ['aa', 'cc', 'bb', 'd', 'a']
  2. B. ['bb', 'cc', 'aa', 'a', 'd'] / ['bb', 'cc', 'aa', 'a', 'd']
  3. C. ['bb', 'cc', 'aa', 'a', 'd'] / ['aa', 'cc', 'bb', 'd', 'a']
  4. D. ['aa', 'cc', 'bb', 'd', 'a'] / ['bb', 'cc', 'aa', 'a', 'd']

Correct answer: B. ['bb', 'cc', 'aa', 'a', 'd'] / ['bb', 'cc', 'aa', 'a', 'd']

sorted with reverse=True preserves the original order of equal elements (stability is kept), exactly like the negated key; it is not the same as reversing the ascending result.

More Python Programming questions

Exams that ask this topic