Length of longest word in a list

coding-style, list, performance, python, string

Solution

I think both are OK, but I think that unless speed is a big consideration that `max(len(w) for w in words)` is the most readable.

When I was looking at them, it took me longer to figure out what `len(max(words, key=len))` was doing, and I was still wrong until I thought about it more. Code should be immediately obvious unless there's a good reason for it not to be.

It's clear from the other posts (and my own tests) that the less readable one is faster. But it's not like either of them are dog slow. And unless the code is on a critical path it's not worth worrying about.

Ultimately, I think more readable is more Pythonic.

As an aside, this one of the few cases in which Python 2 is notably faster than Python 3 for the same task.

Problem

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?).

Original source