[Tutor] assignment statements in python

Kent Johnson kent37 at tds.net
Mon Jun 12 11:59:16 CEST 2006


Kermit Rose wrote:
>   
> Message: 1
> Date: Sun, 11 Jun 2006 06:58:39 -0400
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] buggy bug in my program
> Cc: tutor at python.org
>  
> Assignment in Python is not a copy, it is a name binding. Assignment
> creates a name for an object. If you assign the same object to two
> names, they both are bound to the same thing. If the object is mutable,
> like a list, changes to the object will be seen regardless of which name
> you use to refer to it.
>  
> ******
>  
> I feel a little bit better now that I know that there is a reason for what
> my
> program did.
>  
> However, I still don't have any idea how to copy values from one cell in 
> an array to the adjacent cell in the same array.

You need to copy the value stored in the list, which is itself a list.

> It must be possible, for otherwise, you could not sort an array.

Actually sorting doesn't require copying the values in the list, it just 
requires moving values to different locations of the list.

A list element is somewhat like a name - it is a reference to a value, 
not a container for a value.

If you say
a=[1,2,3]
b=a

then a and b refer to the same list. Likewise, if you say
x=[ [1,2,3], [4,5,6] ]
x[1] = x[0]

then x[1] and x[0] refer to the same list. If you want x[1] (or b) to 
refer to a new list, you have to copy the old list:
x[1] = x[0][:]

list[:] is the slice of the list that goes from the beginning to the end 
- a copy.

Kent



More information about the Tutor mailing list