ProgrammingVery hardProduct-company MCQ pattern

What is printed on the third line?

What is printed on the third line?
names = ['bob', 'Alice', 'carl', 'Bob', 'alice']
print(sorted(names))
print(sorted(names, key=str.casefold))
print(sorted(names, key=lambda s: (s.lower(), s)))
  1. A. ['Alice', 'alice', 'Bob', 'bob', 'carl']
  2. B. ['Alice', 'Bob', 'alice', 'bob', 'carl']
  3. C. ['Alice', 'alice', 'bob', 'carl', 'Bob']
  4. D. ['carl', 'Bob', 'bob', 'alice', 'Alice']

Correct answer: A. ['Alice', 'alice', 'Bob', 'bob', 'carl']

The tuple key compares the lowercase name first and the original text second, so for each name 'Alice' sorts before 'alice' and 'Bob' before 'bob'. Plain sorted() puts all capitals first, which is the trap.

More Python Programming questions

Exams that ask this topic