[Tutor] Length of longest item in a list, using a list comp
Andreas Kostyrka
andreas at kostyrka.org
Thu Dec 28 21:16:31 CET 2006
* Python <python at venix.com> [061228 20:44]:
> On Thu, 2006-12-28 at 11:27 -0800, Tony Cappellini wrote:
> >
> >
> > I want to use a list comp to get the length of the longest string in a
> > list, but can't quite get the syntax right.
> >
> > l1=['abc', 'abcde', 'abcfdtea']
> >
> > longest=0
> > [x for x in l1 if len(x) > longest]
>
> Use max to get the longest
>
> longest = max([len(x) for x in ll])
>
> With versions >= 2.4 you can omit the []
With 2.5 you can even do stuff like that:
>>> x=[range(5), range(3), range(7)]
>>> max(x, key=lambda i: len(i))
[0, 1, 2, 3, 4, 5, 6]
>>>
Andreas
More information about the Tutor
mailing list