ProgrammingVery hardProduct-company MCQ pattern

What is printed?

What is printed?
print(sorted(['10', '9', '2b', '2a']), sorted([10, 9, 2], key=str))
  1. A. ['10', '2a', '2b', '9'] [10, 2, 9]
  2. B. ['10', '2a', '2b', '9'] [2, 9, 10]
  3. C. ['10', '2a', '2b', '9'] [9, 10, 2]
  4. D. ['2a', '2b', '10', '9'] [10, 2, 9]

Correct answer: A. ['10', '2a', '2b', '9'] [10, 2, 9]

String sorting compares character by character, so '10' comes before '2a' because '1' is below '2' and '9' comes last. With key=str the integers are compared as text, which puts '10' before '2' and '9'.

More Python Programming questions

Exams that ask this topic