ProgrammingHardProduct-company MCQ pattern

What is printed on the first line?

What is printed on the first line?
words = ['apple', 'Bob', 'cat', 'Dog', 'ant']
print(sorted(words, key=lambda w: (w[0].lower(), w)))
print(sorted(words, key=lambda w: w.lower(), reverse=True))
  1. A. ['Bob', 'Dog', 'ant', 'apple', 'cat']
  2. B. ['apple', 'ant', 'Bob', 'cat', 'Dog']
  3. C. ['ant', 'apple', 'cat', 'Bob', 'Dog']
  4. D. ['ant', 'apple', 'Bob', 'cat', 'Dog']

Correct answer: D. ['ant', 'apple', 'Bob', 'cat', 'Dog']

The key sorts by the lowercase first letter and then by the full word, so 'ant' comes before 'apple' and 'Bob' comes before 'cat'. Ordering by the whole word would put capitals first, which is the trap.

More Python Programming questions

Exams that ask this topic