[Tutor] Sort Output

Kent Johnson kent37 at tds.net
Wed Sep 17 21:39:57 CEST 2008


On Wed, Sep 17, 2008 at 3:30 PM, Wayne Watson
<sierra_mtnview at sbcglobal.net> wrote:
> I'm using Python 2.4 in Win XP. I was surprised to find the result below.
>
>>>> a =[4,2,5,8]
>>>> b = a
>>>> a.sort()
>>>> a
> [2, 4, 5, 8]
>>>> b
> [2, 4, 5, 8]
>
> b no longer has the same value as it began. Apparently to prevent sort from
> making it the same I have to resort to copying b into a first? What is the
> proper way to retain a variable with the original values of a?

Yes, you have to make a copy. This is as simple as
  b = list(a)

In your original code, a and b refer to the same list.

See
http://personalpages.tds.net/~kent37/kk/00012.html
http://effbot.org/zone/python-objects.htm

Kent


More information about the Tutor mailing list