[Tutor] When max() doesn't work as expected

wescpy at gmail.com wescpy at gmail.com
Fri Dec 4 03:58:55 CET 2009


On Dec 3, 2009, at 18:25, Hugo Arts <hugo.yoshi at gmail.com> wrote:

> On Fri, Dec 4, 2009 at 2:08 AM, Tony Cappellini  
> <cappy2112 at gmail.com> wrote:
>
> I have a list of 2300 strings.
>
> When I call max() on the list, it returned an item with 37  
> characters. I am only passing 1 argument to max().
> I know for a fact that the largest item has 57 characters, [...]
> What are the assumptions when calling max on a list of strings?
>
> Max gives you the largest item in the iterable. That's not the same  
> as the longest item. e.g.:
>
> >>> max(['aaa', 'z'])
> 'z'
> >>> 'aaa' < 'z'
> True
>
> When you're comparing strings, the 'largest' one is not the longest  
> string, but the string that comes last alphabetically speaking. If  
> you want the item whose length is greatest, use the 'key' argument,  
> like so:
>
> >>> max(['aaa', 'z'], key=len)

everyone is spot-on. the whole crux of the problem is that "largest" ! 
= "longest", so that's where 'key' comes in. "largest" (max) means the  
largest lexicographically, so it's ASCII sort order and presumably  
code point order for Unicode -- pls correct me if i'm wrong. and of  
course, the opposite for min/"smallest".

cheers,
-wesley
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091203/21b51e1b/attachment-0001.htm>


More information about the Tutor mailing list