Length of the longest string in a list

EasyString Programs · 2 of 106

Write a Python program that returns the length of the longest string in a list.

Advertisement
Input
["python", "is", "readable", "fun"]
Output
8 | 8 | readable

Approach

  1. Compare lengths in a loop, or use max() with len.

Solution

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

More string programs

← All 106 String Programs

Leave a Comment