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.
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# Find longest8if 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
Check that arr contains a string.
- 2
Call max(arr, key=len).
- 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.
๐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