ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
w = ['pear', 'fig', 'apple', 'kiwi', 'date']
print(sorted(w, key=lambda s: (len(s), s)), sorted(w, key=len, reverse=True))
  1. A. ['fig', 'date', 'kiwi', 'pear', 'apple'] ['apple', 'pear', 'kiwi', 'date', 'fig']
  2. B. ['fig', 'date', 'kiwi', 'pear', 'apple'] ['apple', 'pear', 'date', 'kiwi', 'fig']
  3. C. ['fig', 'date', 'kiwi', 'apple', 'pear'] ['apple', 'pear', 'kiwi', 'date', 'fig']
  4. D. ['fig', 'date', 'pear', 'kiwi', 'apple'] ['apple', 'pear', 'kiwi', 'date', 'fig']

Correct answer: A. ['fig', 'date', 'kiwi', 'pear', 'apple'] ['apple', 'pear', 'kiwi', 'date', 'fig']

The first sort orders by length and then alphabetically. With reverse=True and key=len, equal lengths keep their original order, so pear, kiwi and date stay in input order.

More Python Programming questions

Exams that ask this topic