Why is this?
Matt Hammond
matt.hammond at rd.bbc.co.uk
Wed Aug 10 07:16:46 EDT 2005
Hi Jiri,
On Wed, 10 Aug 2005 11:40:54 +0100, Jiri Barton <jbar at hosting4u.cz> wrote:
> I have a problem with initialization.
>>>> a, b = [[]]*2
>>>> a.append(1)
>>>> b
> [1]
>
> Why is this? Why does not this behave like the below:
>
>>>> a, b = [[], []]
>>>> a.append(1)
>>>> b
> []
In the first case, you make a list containing a single empty list. The
"*2" operation duplicates the item in that list. So now both a and b
contain the same instance of an empty list. Whereas in the second case,
you explicity declare two separate instances of an empty list.
The append method modifys the existing list object - it changes the values
it holds inside itself. Therefore, in the first example, because a and b
both refer to the same object, changing 'a' will will appear to also
change 'b'. The same is not true of the second example, because they are
different objects.
A simpler example:
>>> a = []
>>> b = []
>>> c = b
Now lets try some tests:
>>> a == b
True
>>> b == c
True
Ok - so this shows that a and b, and b and c are equal _in the sense that
they amount to the same value_. But that doesn't mean they are the same
actual object:
>>> a is b
False
>>> b is c
True
b and c are the same empty list object. But a and b are separate,
different, empty list objects.
Why the difference? Imagine you made a set of objects to represent some
kind of numeric values, eg. vectors. Asking "A==B" means "is the value of
the vector A, the same as the value of the vector B". But asking "A is B"
means "is the object A the same object as B".
>>>> [[]]*2
> [[], []]
>>>> [[], []] == [[]]*2
> True
Same effect. But try the 'is' operator, to see if they are actually the
same instances of 'empty list':
>>>> [[], []] is [[]]*2
> True
Hope this helps ... its my first go at explaining this kind of stuff, so
apologies if it isn't as clear as it could be!
Matt
--
| Matt Hammond
| R&D Engineer, BBC Research and Development, Tadworth, Surrey, UK.
More information about the Python-list
mailing list