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?).
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 .
In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With