strings and sort()

Hans Nowak wurmy at earthlink.net
Wed Feb 20 23:45:00 EST 2002


Paul Rubin wrote:
> 
> 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
> > ...
> 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.

True... in this case. He may not always use it with a
listcomp though, and then sort3 will sort the list in
place and return it.

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



More information about the Python-list mailing list