ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
rows = [(2, 'b'), (1, 'z'), (2, 'a'), (1, 'y')]
print(sorted(rows, key=lambda t: (-t[0], t[1])))
  1. A. [(1, 'y'), (1, 'z'), (2, 'a'), (2, 'b')]
  2. B. [(2, 'b'), (2, 'a'), (1, 'z'), (1, 'y')]
  3. C. [(2, 'a'), (2, 'b'), (1, 'z'), (1, 'y')]
  4. D. [(2, 'a'), (2, 'b'), (1, 'y'), (1, 'z')]

Correct answer: D. [(2, 'a'), (2, 'b'), (1, 'y'), (1, 'z')]

The key negates the first field, so larger first values come earlier, and the second field breaks ties in ascending order. Negating a value is the usual trick for a descending sort key that can be combined with an ascending one.

More Python Programming questions

Exams that ask this topic