Why is this?
Matt Hammond
matt.hammond at rd.bbc.co.uk
Fri Aug 12 08:22:52 EDT 2005
On Fri, 12 Aug 2005 12:57:38 +0100, Peter Mott <peter at monicol.co.uk> wrote:
> If I use concatenation + instead of multiplication * then I get the
> result that Jiri expected:
>
> >>> L = [[]] + [[]]
> >>> L[1].append(1)
> >>> L
> [[], [1]]
>
> With * both elements are changed:
>
> >>> L = [[]] * 2
> >>> L[1].append(1)
> >>> L
> [[1], [1]]
>
> Alex Martelli says in his excellent Nutshell book that + is
> concatenation and that "n*S is the concatenation of n copies of S". But
> it seems not so. Surely, from a logical point of view, S + S should be
> the same as S * 2?
S+S is the same as S*2, but L= [[]] + [[]] is not S+S. The two terms being
added are different instances of an empty list. You are
adding/concatenating two different object instances.
Suppose I do concatenate two of the same object instance, then I get the
same behaviour as with the multiply example:
>>> T = [[]]
>>> L = T + T
>>> L[1].append(1)
>>> L
[[1], [1]]
In fact, you could argue this is exactly what the multiply operation is
doing. (internally the implementation may be slightly different, but it is
still equivalent to this)
regards
Matt
--
| Matt Hammond
| R&D Engineer, BBC Research and Development, Tadworth, Surrey, UK.
More information about the Python-list
mailing list