ProgrammingHardTCS NQT · Infosys

What is printed?

What is printed?
print(sorted(['10', '9', '100', '2']), sorted(map(int, ['10', '9', '100', '2'])))
  1. A. ['2', '9', '10', '100'] [2, 9, 10, 100]
  2. B. ['10', '100', '2', '9'] [2, 9, 10, 100]
  3. C. ['10', '100', '2', '9'] [10, 9, 100, 2]
  4. D. ['10', '9', '100', '2'] [2, 9, 10, 100]

Correct answer: B. ['10', '100', '2', '9'] [2, 9, 10, 100]

Sorting strings compares them character by character, so '10' < '100' < '2' < '9'. Converting to int first gives numeric order, which is the usual fix for this trap.

More Python Programming questions

Exams that ask this topic