strings and sort()

Remco Gerlich scarblac at pino.selwerd.nl
Thu Feb 21 08:41:39 CET 2002


Jason <caljason76 at yahoo.com> wrote in comp.lang.python:
> How do I sort the characters in a string, so far I use this:
>         a="qwerasdfzxcv"
>         b=[x for x in a]
>         b.sort()

Yes. Instead of b=[x for x in a] you can use b = list(a).

> Why doesn't sort() return the sorted list.  I would like to chain it
> to other operations:
>         b=[x for x in a].sort()

sort() sorts the list in place, probably because that's usually what you
want. Methods that change the object in place typically don't return the
object, or people might think that the object wasn't changed.

Like

b=[4,3,2,1]
c=b.sort()

People might believe that b wasn't changed. To avoid confusion, you can't do
that.

-- 
Remco Gerlich



More information about the Python-list mailing list