Use max with key=len .
In [3]: max([l1, l2], key=len) Out[3]: [4, 5, 6, 7]
This will result in a (first) long list for the list of lists.
In fact, this will also work with strings (and other objects with the len attribute).
In [4]: max(['abcd', 'ab'], key=len) Out[4]: 'abcd' In [5]: max([(1, 2), (1, 2, 3), (1,)], key=len) Out[5]: (1, 2, 3) In [6]: max(['abc', [1, 2, 3]], key=len) Out[6]: 'abc'
Note: we can also pass elements as arguments:
In [7]: max(l1, l2, key=len) Out[7]: [4, 5, 6, 7]
max reads: get me the largest element in the list when (if you pass key ) looking from the point of view of key .
This is roughly equivalent to the following code * (in python 3), but the actual source is written in C (much more efficient, and in fact, please continue to use max, not that!):
def my_max(*L, key=None): # in python 2 we'd need to grab from kwargs (and raise type error if rogue keywords are passed) L = list(L[0]) if len(L) == 1 else L # max takes iterable as first argument, or two or more arguments... if not L: raise ValueError("my_max() arg is an empty sequence") if key is None: # if you don't pass a key use the identity key = lambda x: x max_item, max_size = L[0], key(L[0]) for item in L[1:]: if key(item) > max_size: max_item, max_size = item, key(item) return max_item
* I leave this as an exercise to write it using iterators, not lists ... and fix any other errors!