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

Hugo Arts hugo.yoshi at gmail.com
Fri Dec 4 03:25:58 CET 2009


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, and when I
> called mylist.index('my_57_character_string') the index was found.
>
> Printing len(mylist[index]) does indeed return 57 characters.
>
> What are the assumptions when calling max on a list of strings?
> Does the list need to be sorted? In my case, the list is sorted.
>
> Does max have any undocumented limitations I'm not aware of?
>
>
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)
'aaa'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091204/08fcc9c7/attachment.htm>


More information about the Tutor mailing list