LearnFrenzy
Sign in Take a free test

Lambda Functions · Predict the Output · Question 2

Sorting by length, then alphabetically Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following Python program?

main.py
words = ["kiwi", "fig", "banana", "apple", "date"]
print(sorted(words, key=lambda w: (len(w), w)))
  • A ['fig', 'kiwi', 'date', 'apple', 'banana']
  • B ['apple', 'banana', 'date', 'fig', 'kiwi']
  • C ['banana', 'apple', 'kiwi', 'date', 'fig']
  • D ['fig', 'date', 'kiwi', 'apple', 'banana'] Correct
Correct Answer: Option D

The tuple key sorts by length first; "date" and "kiwi" both have 4 letters and are then ordered alphabetically.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links