[Tutor] Sort Output
Jerry Hill
malaclypse2 at gmail.com
Wed Sep 17 21:40:16 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
This binds the name "b" to the same object that "a" is bound to.
>>>> 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. If you want "a" and "b" to point to different lists, you'll need
to copy the list that "a" is bound to. This is a really common thing
to do, and python provides an easy way to do it:
>>> a = [4, 2, 5, 8]
>>> b = sorted(a)
>>> print a
[4, 2, 5, 8]
>>> print b
[2, 4, 5, 8]
>>>
--
Jerry
More information about the Tutor
mailing list