[Tutor] Sort Output
Alan Gauld
alan.gauld at btinternet.com
Thu Sep 18 02:43:23 CEST 2008
"Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote
> I was surprised to find the result below.
Well done, you just found one of the standard beginners gotchas!
>>>> a =[4,2,5,8]
>>>> b = a
This makes b refer to the *same list* as a.
>>>> a.sort()
This sorts the list contents in-place
>>>> a
> [2, 4, 5, 8]
As shown.
>>>> b
> [2, 4, 5, 8]
And since b refers to the same luist as a it also reflects
the rearrangement of the contents.
> b no longer has the same value as it began.
Actually it does. It refers to exactly the same list as a
before and after the sort. The list object has not changed
only the contents of the list were sorrted.
> Apparently to prevent sort from making it the same
> I have to resort to copying b into a first?
No you need to take a copy of a when you assign it to b
b = a[:]
will result in b referring to a copy of a.
Now if you change a's list nothing will happen to b's copy
Remember that in Python variables are just names that
refer to objects. Many names can refer to the same object.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list