Built-ins & Standard Library · Question 15 · Medium

sorted is given a key that returns a tuple, to rank students by marks (high to low) and then by name. In what order do the names come out?

students = [("Ravi", 80), ("Anu", 92), ("Meera", 80)]
ranked = sorted(students, key=lambda s: (-s[1], s[0]))
print([name for name, marks in ranked])
  1. ['Anu', 'Ravi', 'Meera']
  2. ['Meera', 'Ravi', 'Anu']
  3. ['Anu', 'Meera', 'Ravi', 80]
  4. ['Anu', 'Meera', 'Ravi']
Answer and explanation

Answer: D. ['Anu', 'Meera', 'Ravi']

Explanation: Tuples are compared item by item. The negated marks put 92 first, and for the two students tied at 80 the second item, the name, decides: Meera comes before Ravi.

Previous: itertools is used to count the 2-item combinations and the 2-item permutations… · Next: itertools.groupby is applied directly to a string in which one letter appears…

Practise built-ins & standard library

Try a fresh set of built-ins & standard library questions with an explanation after every answer, free and without signing up: Built-ins & Standard Library practice. Or sit a full placement mock test.

More built-ins & standard library questions

More python practice

Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators · Classes & Objects

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge