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])
- ['Anu', 'Ravi', 'Meera']
- ['Meera', 'Ravi', 'Anu']
- ['Anu', 'Meera', 'Ravi', 80]
- ['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
- zip is used with the * operator to split a list of pairs. What does this code…
- A file tools.py ends with a block under if __name__ == "__main__":. When does…
- itertools is used to count the 2-item combinations and the 2-item permutations…
- itertools.groupby is applied directly to a string in which one letter appears…
- Booleans are used in an isinstance check, in addition and inside sum. What…
- A program imports the same module helper from two different files. How many…
- A defaultdict(int) is updated for one key, read for a second key and tested…
- all, any and max are each given an empty list, with a default supplied to max…
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