strings and sort()

Paul Rubin phr-n2002a at nightsong.com
Wed Feb 20 23:21:18 EST 2002


Hans Nowak <wurmy at earthlink.net> writes:
> > 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
> ...
> 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.

Just write it like this:

def sort3(lst):
  lst.sort()
  return lst

The list comprehension already makes a temporary list.  You don't need
to copy it around again.



More information about the Python-list mailing list