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

Kent Johnson kent37 at tds.net
Fri Dec 4 03:22:40 CET 2009


On Thu, Dec 3, 2009 at 8:08 PM, 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() finds the 'largest' in sort order. Strings sort in dictionary order so
the max of a list strings will be the one that comes last in dictionary
order.

The key= argument to sort lets you modify the way list items are compared;
instead of using the default comparison of list objects, the corresponding
keys are compared.

Try
  max(my_list, key=len)
to use the length of the strings as the key and find the longest string.

Kent

>
>   *max*( iterable[, args...][key]) With a single argument iterable, return
> the largest item of a non-empty iterable (such as a string, tuple or list).
> With more than one argument, return the largest of the arguments.
>
> The optional key argument specifies a one-argument ordering function like
> that used for list.sort(). The key argument, if supplied, must be in
> keyword form (for example, "max(a,b,c,key=func)"). Changed in version 2.5:
> Added support for the optional key argument.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091203/5d311d2b/attachment.htm>


More information about the Tutor mailing list