Python Practice › String Programs › Program 2
Length of the longest string in a list
Write a Python program that returns the length of the longest string in a list.
Input
["python", "is", "readable", "fun"]
Output
8 | 8 | readable
Approach
- Compare lengths in a loop, or use
max()withlen.
Solution
words = ["python", "is", "readable", "fun"]longest = 0for w in words: if len(w) > longest: longest = len(w)print(longest, "|", max(len(w) for w in words), "|", max(words, key=len))Output
8 | 8 | readable
Line by line
Lines 3-5
Keep the biggest length seen so far.
Line 6
max(len(w) for w in words) does the same in one line; max(words, key=len) returns the word itself.
Learn the concept
New to this topic? Read the lesson, then come back.