[Tutor] Length of longest item in a list, using a list comp

Tony Cappellini cappy2112 at gmail.com
Thu Dec 28 21:14:31 CET 2006


Thanks,
but I am restricted to using 2.3.4 for now, so

longest = max([len(x) for x in ll])

works for me


On 12/28/06, Andreas Kostyrka <andreas at kostyrka.org> wrote:
>
> * 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061228/032d087a/attachment.html 


More information about the Tutor mailing list