ProgrammingHardTCS NQT · Wipro pattern

What is printed?

What is printed?
import heapq
words = ['bb', 'a', 'cc', 'dd', 'e']
print(heapq.nlargest(2, words, key=len), heapq.nsmallest(2, words, key=len))
  1. A. ['bb', 'cc'] ['a', 'e']
  2. B. ['dd', 'cc'] ['a', 'e']
  3. C. ['bb', 'cc'] ['e', 'a']
  4. D. ['cc', 'dd'] ['a', 'e']

Correct answer: A. ['bb', 'cc'] ['a', 'e']

nlargest and nsmallest behave like a stable sort on the key, so among equal lengths the earlier word wins. For the smallest lengths, 'a' comes before 'e'.

More Python Programming questions

Exams that ask this topic