Python bootcamp · Lab 47

Sort by length

mediumLambda12 minLesson: Lambda

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a line of words and print them sorted by length (shortest first), space-separated.

Ties keep their original order — Python's sort is stable. Pass a lambda as the key.

Input. One line of space-separated words.

Output. The words sorted by length, space-separated.

Examples

Example 1
Input
cat elephant a dog
Output
a cat dog elephant
Example 2 — bb and cc are the same length, so original order stays.
Input
bb a cc
Output
a bb cc
Hint
  1. sorted(words, key=lambda w: len(w))
  2. print(*...) to space them out.
Show correct code

Peek only after you have tried. You can still Check your own version.

words = input().split()
print(*sorted(words, key=lambda w: len(w)))
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.