Why is this?
Duncan Booth
duncan.booth at invalid.invalid
Fri Aug 12 08:29:58 EDT 2005
Peter Mott 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?
>
What you did was not S+S. You did S+T, i.e. you added two distinct lists.
Try it again adding the same list and you will see that both addition and
multplication do work the same:
>>> S = [[]]
>>> L = S + S
>>> L[1].append(1)
>>> L
[[1], [1]]
>>> S = [[]]
>>> L = 2*S
>>> L[1].append(1)
>>> L
[[1], [1]]
More information about the Python-list
mailing list