ProgrammingVery hardTCS NQT · Accenture

What is printed?

What is printed?
print(sorted(['b2', 'a10', 'a9', 'b1'], key=lambda s: (s[0], int(s[1:]))), sorted(['b2', 'a10', 'a9', 'b1']))
  1. A. ['a9', 'a10', 'b1', 'b2'] ['a10', 'a9', 'b1', 'b2']
  2. B. ['a10', 'a9', 'b1', 'b2'] ['a9', 'a10', 'b1', 'b2']
  3. C. ['a9', 'a10', 'b1', 'b2'] ['a9', 'a10', 'b1', 'b2']
  4. D. ['a9', 'b1', 'a10', 'b2'] ['a10', 'a9', 'b1', 'b2']

Correct answer: A. ['a9', 'a10', 'b1', 'b2'] ['a10', 'a9', 'b1', 'b2']

The first key compares the letter and then the number, so a9 comes before a10. The plain sort compares strings character by character, so '10' sorts before '9' inside the a group.

More Python Programming questions

Exams that ask this topic