Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of longest word in a list

What is the more pythonic way of getting the length of the longest word:

len(max(words, key=len))

Or:

max(len(w) for w in words)

Or.. something else? words is a list of strings. I am finding I need to do this often and after timing with a few different sample sizes the first way seems to be consistently faster, despite seeming less efficient at face value (the redundancy of len being called twice seems not to matter - does more happen in C code in this form?).

like image 973
wim Avatar asked Feb 01 '13 00:02

wim


People also ask

How do you find the longest word in a list?

Use max() to find the longest string in a list. Call max(a_list, key=len) to return the longest string in a_list by comparing the lengths of all strings in a_list .

How do I find the max length of a word in Python?

In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length.

How do you find the longest string in a list Python?

Use Python's built-in max() function with a key argument to find the longest string in a list. Call max(lst, key=len) to return the longest string in lst using the built-in len() function to associate the weight of each string—the longest string will be the maximum.


1 Answers

Although:

max(len(w) for w in words)

does kind of "read" easier - you've got the overhead of a generator.

While:

len(max(words, key=len))

can optimise away with the key using builtins and since len is normally a very efficient op for strings, is going to be faster...

like image 170
Jon Clements Avatar answered Sep 22 '22 13:09

Jon Clements