ProgrammingHardProduct-company MCQ pattern

What is printed on the second line?

What is printed on the second line?
words = ['bb', 'a', 'ccc', 'dd', 'e']
print(sorted(words, key=len))
print(sorted(words, key=len, reverse=True))
print(sorted(words, key=lambda w: -len(w)))
  1. A. ['ccc', 'dd', 'bb', 'e', 'a']
  2. B. ['ccc', 'bb', 'dd', 'e', 'a']
  3. C. ['a', 'e', 'bb', 'dd', 'ccc']
  4. D. ['ccc', 'bb', 'dd', 'a', 'e']

Correct answer: D. ['ccc', 'bb', 'dd', 'a', 'e']

reverse=True keeps the input order of equal-length words, so bb comes before dd and a before e. Sorting by -len also keeps this order because it is a stable sort on the same key.

More Python Programming questions

Exams that ask this topic