Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

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']

In this one

  • Sort through key functions
  • Retain stable ties
  • Avoid mutating the source

How it works

  1. 1

    Collect the string list.

  2. 2

    Call sorted(arr, key=len).

  3. 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.