1
\$\begingroup\$

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?

janos
113k15 gold badges154 silver badges396 bronze badges
asked May 24, 2015 at 0:51
\$\endgroup\$
2
  • \$\begingroup\$ How long lists are we dealing with? Are you sure you need a list? What kind of lists? \$\endgroup\$ Commented May 24, 2015 at 0:56
  • \$\begingroup\$ @SimonAndréForsberg see edit, I hope it's clearer now. \$\endgroup\$ Commented May 24, 2015 at 1:14

1 Answer 1

4
\$\begingroup\$

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)
answered May 24, 2015 at 7:31
\$\endgroup\$
1
  • \$\begingroup\$ with more than 1 argument does the key=len need to be in brackets? max(a,b,c, [key=len])? \$\endgroup\$ Commented Sep 12, 2019 at 10:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.