Sort Strings by Length
Sort a Python list of strings by increasing length. Students use key=len, retain input order for equal lengths, and create a new list without altering arr.
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']
In this one
- Sort through key functions
- Retain stable ties
- Avoid mutating the source
How it works
- 1
Collect the string list.
- 2
Call sorted(arr, key=len).
- 3
Print sorted_arr with its length-based ordering.
Edge cases
Are ties alphabetically sorted?
Are ties alphabetically sorted?
No. Equal lengths keep input order.
Does this mutate arr?
Does this mutate arr?
No. sorted creates a new list.
What's going on
sorted(arr, key=len) measures each string's length for ordering. It returns a new list rather than modifying arr.
Python sorting is stable, so equal-length strings retain their relative input order. Spaces contribute to length because the strings are not trimmed. Empty strings sort before nonempty strings; an empty collection simply produces another empty list.
Are ties alphabetically sorted? No. Equal lengths keep input order.
Does this mutate arr? No. sorted creates a new list.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which string comes first by length?
Pick an answer to check it.
Question 2
Are ties alphabetically sorted?
Pick an answer to check it.
Questions people ask
Are ties alphabetically sorted?
No. Equal lengths keep input order.
Does this mutate arr?
No. sorted creates a new list.
Which string comes first by length?
An empty string, if present.
๐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