[Tutor] sort list alphabetically

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Nov 24 01:47:22 CET 2005


> In python2.4, you can also use the key= keyword argument:
>
> ###
> def toUpper(s):
>  return s.upper()
> files.sort(key=toUpper)
> ###
>
> This is more efficient, I believe, because the key function is only
> called once for each element, whereas cmp is called more than once.
>
> (we could use string.upper here instead of defining our own, but
>  string.upper is deprecated these days...)

Hi John,

The 'string' module might be deprecated, but the 'str' type should be
fine:

######
>>> names = ['bill', 'Ted', 'Excellent']
>>> names.sort()
>>> names
['Excellent', 'Ted', 'bill']
>>> names.sort(key=str.upper)
>>> names
['bill', 'Excellent', 'Ted']
######

Best of wishes!



More information about the Tutor mailing list