strange side effect with lists!?

Fredrik Lundh fredrik at pythonware.com
Wed Oct 13 05:24:56 EDT 2004


Wolfgang.Stoecher at profactor.at wrote:

> I'm new to Python and playing around. I'm confused by the following
> behaviour:
>
>>>> l1 = [1] # define list
>>>> l2 = l1  # copy of l1 ?

nope.  plain assignment simple adds another name for the same object.

>>>> l2,l1
> ([1], [1])
>>>> l2.extend(l1) # only l2 should be altered !?
>>>> l2,l1
> ([1, 1], [1, 1]) # but also l1 is altered!
>
> So what is the policy of assignment? When is a copy of an object created?

never, unless you say so.

> Where to find dox on this?

any decent tutorial should explain this.

for a more focussed discussion, see:

    http://www.effbot.org/zone/python-objects.htm
    (short version)

    http://starship.python.net/crew/mwh/hacks/objectthink.html
    (longer version)

</F> 






More information about the Python-list mailing list