what is the keyword "is" for?

daniel daniel.huangfei at gmail.com
Tue Aug 15 04:34:21 EDT 2006


Martin v. Löwis wrote:
> daniel wrote:
> > when I tried to check the stuff out, found sth interesting that if you
> > define variables in a style like this:
> > a = b = ['a', 'b']
> > changing one list affects the other, and they still refer to same
> > object. in fact, seems all compound types (dictionary for instance)
> > behave in this way.
> >
> > however, when list is replaced with other built-in  types like integers
> > :
> > a = b = 3
> > changing one of them cause the two objects differ...
>
> Ah, but make a difference between "change a variable", and "change an
> object".
>
> py> a = b = [1,2,3]
> py> a[0] = 6   # don't change the variable a, just change the object
> py> a
> [6, 2, 3]
> py> b
> [6, 2, 3]
> py> a=[7,8,9]  # change the variable a;
>                # it's now a different object than b
mm, python runtime might allocate a new chunk of memory for this... but
might not for the previous operation..
> py> a
> [7, 8, 9]
> py> b
> [6, 2, 3]
>
> For some objects, "change the object" is impossible. If you have
>
> a = b = 3
>
> then there is no way to change the object 3 to become 4 (say);
> integer objects are "immutable". So for these, to make a change,
> you really have to change the variable, not the value.
>
sounds reasonable, I tried tuple which is also immutable, it behaves
the same as integers. 

> Regards,
> Martin

tks Martin...




More information about the Python-list mailing list