simple newbie question

Mike Meyer mwm at mired.org
Tue Dec 10 21:46:51 EST 2002


eugene kim <eugene1977 at hotmail.com> writes:

> what's different in these two..assignment, append?
> thank you
> 
> listvar1 = [1]
        -- sets listvar1 to a list containing 1

> listvar2 = listvar1
        -- sets listvar2 to the same list as listvar1
     
> listvar2 = [2]
        -- sets listvar2 to a list containing 2

---
> listvar1 = [1]
        -- as above
> listvar2 = listvar1
        -- as above
> listvar2.append(2)
        -- appends 2 to the list pointed to by listvar1 and listvar2

The hardest thing for people coming from compiled procedural languages
is that Python variables are all(*) *references* to objects. This
doesn't make any difference for simple objects list numbers, but for
complex objects like lists and instances, it makes a *lot* of
difference. Because after an assignment like "var2 = var1", var1 and
var2 aren't simply two objects that are now equal, they both *refer*
to the same object. So when you do things that modify var1, var2 will
show those changes because it's the same object.

If you're used to C, it's the difference between:
        struct Foo v1, v2, *vp1, *vp2;

        Foo_fill(&v1);
        v2 = v1;                /* 1 */
        vp1 = &v1;
        vp2 = vp1;              /* 2 */

You now have two Foo's, v1 and v2. vp1 and vp2 both point at
v1. Python assignment is like statement #2, *not* statement #1.

        <mike

*) Ok, not all. But this is only false for things where it doesn't
make any difference.

-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list