Sort Words by Length
Advanced · Write the code · from Python Lambda Functions: When to Use (and When Not To)
From the lesson: Python Lambda Functions: When to Use (and When Not To)
Imagine you need to leave someone a quick note: "Back in 5 minutes." You wouldn't write a formal letter with a greeting, three paragraphs, and a signature. You'd scribble it on a sticky note and be done.
Read the lessonGiven a list of words, use sorted() with a lambda to sort them by length (shortest first). If two words have the same length, they should appear in alphabetical order. Print the sorted list.
Use this list: words = ['fig', 'apple', 'date', 'kiwi', 'banana', 'pear', 'plum']
Expected output: ['fig', 'date', 'kiwi', 'pear', 'plum', 'apple', 'banana']
words = ['fig', 'apple', 'date', 'kiwi', 'banana', 'pear', 'plum']
# Sort by length, then alphabetically
More Lambda exercises
- Predict the Lambda OutputBeginner
- Sort by Last CharacterBeginner
- Filter and TransformIntermediate
- Sort Students by GPAIntermediate
All Python exercises · 50 practice problems · Functions quiz