Logic Building
# Take array of strings
n = int(input("Enter number of strings: "))
arr = []
for i in range(n):
arr.append(input(f"String {i+1}: "))
# Sort by length
sorted_arr = sorted(arr, key=len)
print(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']
Use sorted() with key=len.
Key Concepts:
- sorted() sorts list
- key=len uses length for comparison
- Returns sorted list