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 strings2n = int(input("Enter number of strings: "))3arr = []4for i in range(n):5 arr.append(input(f"String {i+1}: "))67# Sort by length8sorted_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
🔗Related Content
- 📖
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- 📝
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- 💻
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum