Creating a List of Empty Lists
Mel Wilson
mwilson at the-wire.com
Fri Dec 5 12:32:14 EST 2003
In article <8089854e.0312050419.2cf36e34 at posting.google.com>,
michael at foord.net (Fuzzyman) wrote:
>Right - because if I do something like :
>
>a = 4
>b = a
>a = 5
>print b
>
>It prints 4... not 5.
>In other words - the line b = a creates a name pointing to the object
>4, rather than a name pointing to the contents of a.....
>
>I think I see what you mean - since the object 4 is immutable......
>the line a = 5 destroys the old name a and creates a new one pointing
>to object 5, rather than changing what the name a is pointing to.
Take care.. forgetting the old binding and replacing it
with the new one doesn't depend on 4 being immutable:
Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a=[4]
>>> b=a
>>> a=5
>>> print b
[4]
>>> print a
5
It's more because the `a` in `a=` is simply a name, and
the rule for assigning to a name is to forget the previous
binding (if any) and create a new binding.
If you say `a[0]=` instead, that's a different rule.
If `a` referred to an immutable object then it (probably)
would make no sense to say `a[0]=`. ("Probably" because
people can do the damndest things with class definitions.
Can't trust 'em.:)
>Since lists and dictionaries are mutable..... changing the contents
>modifies the object rather than destroying the refereence tothe old
>one and creating a new one.....
Lists and dictionaries are mutable, and it does make
sense to say `some_list[some_index] = `. When you do *this*,
the python-object-reference kept in `some_list` at position
`some_index` is forgotten, and is replaced by a new
python-object-referemce. Something similar will happen
with a dictionary.
Also with code like `some_instance.some_attribute =`
which you could think of as re-binding `some_attribute` or
as mutating `some_instance.__dict__`.
Regards. Mel.
More information about the Python-list
mailing list