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

Find Longest String in Array

Choose the longest string in a Python list using max with key=len. Students include spaces in length and handle tied maxima or an empty collection explicitly.

IntermediatePhase 6 - Category 2: Array & String CombinationsExample 4 of 10
find-longest-string-in-array.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# Find longest
8if arr:
9 longest = max(arr, key=len)
10 print(f"Longest string: {longest}")
11else:
12 print("Array is empty")

Output

Enter number of strings: 3
String 1: Hello
String 2: World
String 3: Programming
Longest string: Programming

In this one

  • Select by complete-string length
  • Handle an empty collection
  • Keep first tied maxima

How it works

  1. 1

    Check that arr contains a string.

  2. 2

    Call max(arr, key=len).

  3. 3

    Print the selected string or the empty-array message.

Edge cases

What if longest lengths tie?

What if longest lengths tie?

The first encountered tied string is returned.

Does an empty stored string make arr empty?

Does an empty stored string make arr empty?

No. A one-entry list is still nonempty.

What's going on

The arr guard checks that a candidate exists. max(arr, key=len) then compares complete string lengths rather than lexical ordering.

The first longest string wins a tie. Spaces count toward length because no stripping occurs. A list containing one empty string is nonempty and selects that empty string, which differs from having no strings at all and printing Array is empty.

What if longest lengths tie? The first encountered tied string is returned.

Does an empty stored string make arr empty? No. A one-entry list is still nonempty.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does key=len compare?

Pick an answer to check it.

Question 2

What if longest lengths tie?

Pick an answer to check it.

Questions people ask

What if longest lengths tie?

The first encountered tied string is returned.

Does an empty stored string make arr empty?

No. A one-entry list is still nonempty.

What does key=len compare?

String lengths.