0

How would I get the longest item in the following list comprehension?

lc = [item.decode('utf-8') for l in srt_breakdown.values() for item in l]

Here is how I would get it's length:

max_length = max([len(item.decode('utf-8')) for l in srt_breakdown.values() for item in l]

How would I get the actual text of the max_length item?

David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

1

Use the key keyword argument; set it to len to find the longest string:

max_length = max(
    (item.decode('utf-8') for l in srt_breakdown.values() for item in l),
    key=len)

Note that I used a generator expression so as not to build the whole list of strings in memory first; instead strings are decoded as needed.

max() will return the first string whose key(element) result is highest. By using len as the key that means that max() will find the longest string.

mgilson
  • 300,191
  • 65
  • 633
  • 696
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343