Library function for sorting

Matthew Dixon Cowles matt at mondoinfo.com
Tue Oct 16 23:49:06 EDT 2001


On 17 Oct 2001 02:06:33 GMT, Michael Yuen <myuen at acs2.acs.ucalgary.ca>
wrote:

Dear Michael,

>I'm really new to this Python stuff

Then welcome!

>and was wondering if there's a library function for sorting strings.
>I sure there is one but haven't been able to find one when I looked
>through the documentation.

It's hiding in the methods for lists. It's documented at:

http://www.python.org/doc/current/lib/typesseq-mutable.html#l2h-73

Here's an example:

>>> foo=["c","b","a"]
>>> foo.sort()
>>> foo
['a', 'b', 'c']

There are a couple of things worth noting about it:

First, it modifies the list in place and returns None. So

>>> bar=foo.sort() # Wrong!

is never what you want. Doing things that way is a matter of
efficiency: Python doesn't want to make copies of large lists when you
don't need them.

Second, the items of the list can be lists or tuples or various
other things:

>>> foo=[("c",2),("b",1),("b",0)]
>>> foo.sort()
>>> foo
[('b', 0), ('b', 1), ('c', 2)]

Third, you can pass a comparison function to sort() but you often
don't want to because that slows things down a lot. This works:

>>> def compareFromSecondCharOn(a,b):
...   return cmp(a[1:],b[1:])
... 
>>> foo=["azz","baa"]
>>> foo.sort(compareFromSecondCharOn)
>>> foo
['baa', 'azz']

But it's often faster to build up a tuple that can be sorted directly
and then tear it apart:

>>> foo=["azz","baa"]
>>> for count in range(len(foo)):
...   foo[count]=(foo[count][1:],foo[count])
... 
>>> foo
[('zz', 'azz'), ('aa', 'baa')]
>>> foo.sort()
>>> foo
[('aa', 'baa'), ('zz', 'azz')]
>>> for count in range(len(foo)):
...   foo[count]=foo[count][1]
... 
>>> foo
['baa', 'azz']

That's a little harder to read but much faster for lists of any
significant length.

Regards,
Matt



More information about the Python-list mailing list