Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have the following code to find the longest list in a list of lists:

max_len = max([len(path) for path in paths])
[path for path in paths if len(path) == max_len][0]

Each path is a list of integers. paths doesn't have to be a list. So if I have, for example:

path_a = [1, 2, 3]
path_b = [1, 4]
path_c = [3, 5, 6, 2, 7]

Then the code should give me path_c. In case of ties, it doesn't matter what's returned as long as it has the correct (longest) length.

Is there a more pythonic way?

share|improve this question
    
How long lists are we dealing with? Are you sure you need a list? What kind of lists? –  Simon Forsberg May 24 at 0:56
    
@SimonAndréForsberg see edit, I hope it's clearer now. –  jcm May 24 at 1:14

1 Answer 1

up vote 2 down vote accepted

Note that your code iterates over paths twice: once to calculate the max length, and one more time to find all elements that have the max length.

It would be better to iterate only once, keeping track of the max value, and the item that had the max value. At the end of the iteration (single pass), return the item that had the max value.

You can code this algorithm yourself, and in many programming languages you would have to. In Python, the max built-in takes a key parameter, to perform such "max by" operation. The key parameter must be a one-argument function. For each item in the collection, the function will receive the item, and should return a value that will be used as the rank of the item.

In your example, the rank of each item is its length. That gives this simple pythonic code:

max(paths, key=lambda coll: len(coll))

... which gets even simpler with η-reduction to just (thanks @Gareth!):

max(paths, key=len)
share|improve this answer
    
Oh crap, you're so right.... Thanks Gareth! –  janos May 24 at 8:07
    
Yes, key does the trick! –  jcm May 25 at 11:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.