Skip to content Skip to sidebar Skip to footer

Sort A List Of Strings By Their Lengths

words = ['dog', 'apple', 'bear'] def len_words(words): w1 = [] for p in words: w1.append(len(p)) pass for p in words: words.sort(key=len_wo

Solution 1:

This should work:

words = ["dog", "apple", "bear"]    
words.sort(key=len)

Solution 2:

No need to define your own length function, just use key=len to sort by length using the built-in len function;

>>> words = ["dog", "apple", "bear"]
>>> words.sort(key=len)
>>> words
['dog', 'bear', 'apple']

Post a Comment for "Sort A List Of Strings By Their Lengths"