Sort Strings by Length

Sort array of strings by length.

IntermediatePhase 6 - Category 2: Array & String CombinationsExample 8 of 10
sort-strings-by-length.py
1# Take array of strings
2n = int(input("Enter number of strings: "))
3arr = []
4for i in range(n):
5 arr.append(input(f"String {i+1}: "))
6
7# Sort by length
8sorted_arr = sorted(arr, key=len)
9print(f"Sorted by length: {sorted_arr}")

Output

Enter number of strings: 4
String 1: programming
String 2: hello
String 3: world
String 4: hi
Sorted by length: ['hi', 'hello', 'world', 'programming']

What's going on

Use sorted() with key=len.

Key Concepts:

sorted() sorts list
key=len uses length for comparison
Returns sorted list