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

Pete Shinners shredwheat at mediaone.net
Sat Jun 2 13:40:50 EDT 2001


"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 ?

hello franz. what this syntax means is,
replace the contents of a list with a different list.

the reason "sys.path = L" does not work, is it actually
changes sys.path to reference a different list. the original
sys.path list is unchanged in memory.

on its own this could work other way, but consider when more
than one variable is referencing the same list. for example:

>>> list1 = [1,2,3]
>>> list2 = list1
>>> print list1, list2
[1, 2, 3] [1, 2, 3]
>>> print id(list1), id(list2)
7937452 7937452

#now lets try changing with the [:] syntax
>>> list1[:] = [4,5,6]
>>> print list1, list2
[4, 5, 6] [4, 5, 6]
>>> print id(list1), id(list2)
7937452 7937452

#now we'll change without the [:] syntax
>>> list1 = [7,8,9]
print list1, list2
[7, 8, 9] [4, 5, 6]
7936508 7937452


hopefully this examples well enough what i've described
up top. :]






More information about the Python-list mailing list