strings and sort()

Hans Nowak wurmy at earthlink.net
Wed Feb 20 23:06:18 EST 2002


Jason wrote:
> 
> How do I sort the characters in a string, so far I use this:
>         a="qwerasdfzxcv"
>         b=[x for x in a]
>         b.sort()
> 
> Why doesn't sort() return the sorted list.  I would like to chain it
> to other operations:
>         b=[x for x in a].sort()

The other replies told you why list.sort() doesn't return
the sorted list. You can easily roll your own function,
though:

>>> def sort2(lst):
	z = lst[:]
	z.sort()
	return z

>>> a = [1, 4, 6, 2, 9, -2]
>>> b = sort2(a)
>>> b
[-2, 1, 2, 4, 6, 9]
>>> a
[1, 4, 6, 2, 9, -2]

This sort2() function returns a new, sorted list
without affecting the original one. Don't use this
when performance is an issue, though... it's not
very efficient because it copies the original
list first.

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) 
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/



More information about the Python-list mailing list