Sort Strings by Length

Easy ⏱ 8 min 75% acceptance ★★★★★ 4.5
Write sort_by_length(words) that returns a new list of the strings in words sorted by length ascending, using sorted() with a key function. For strings of equal length, preserve their original relative order.

Examples

Example 1
Input
words = ['banana', 'fig', 'kiwi', 'a']
Output
['a', 'fig', 'kiwi', 'banana']
Explanation

Sorted by len(); sort is stable so equal-length ties keep original order.

Constraints

  • 0 <= len(words) <= 10^4

Topics

ListsSorting

Companies

NetflixIBM

Hints

Hint 1

sorted(words, key=len) sorts by each string's length.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.