ProgrammingHardTCS NQT · Wipro pattern

What is printed?

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

Correct answer: C. ['ccc', 'aa', 'bb', 'a']

The key sorts by length in descending order and then alphabetically. ccc is the longest, then aa and bb in alphabetical order, and the single letter a comes last.

More Python Programming questions

Exams that ask this topic