What does x[:]=[4,5,6] mean?

Jonathan Gardner gardner at cardomain.com
Mon Jun 4 15:07:24 EDT 2001


Indirect Meowbot wrote:

> "Franz GEIGER" <fgeiger at datec.at> wrote:
> 
>> In site.py I saw
>> sys.path[:] = L
>> What does this mean? Why is the '[:]'? Why not simply
>> sy.path = L ?
> 
> In a language like C you have to work a little bit harder to get a
> pointer to something.  In Python, you have to work a little bit harder
> _not_ to get just a reference.
> 
>>>> meow = [1,2,3]
>>>> woof = meow
>>>> meow[0] = 42
>>>> print meow, woof
> [42, 2, 3] [42, 2, 3]
>>>> # Ewww!
> ...
>>>> meow = [1,2,3]
>>>> woof[:] = meow
>>>> meow[0] = 42
>>>> print meow, woof
> [42, 2, 3] [1, 2, 3]
>>>> # Yay.

The bottom line is the assignment operator _never_ makes a copy of 
something - the end result is to make the variables point to the object on 
the right hand side.

Try this:
>>> a = 3
>>> b = a
>>> id (a)
135045160
>>> id (b)
135045160
>>> # What? a and b are the SAME OBJECT!
>>> b += 1
>>> id (a)
135045160
>>> id (b)
135045148
>>> # Now they are different

So, the only "value" that the variables hold in python is the address of 
whatever object they are pointing to. Therefore, every variable in Python 
is a reference, or a pointer, whatever you prefer.





More information about the Python-list mailing list