Why is this?
Peter Mott
peter at monicol.co.uk
Fri Aug 12 07:57:38 EDT 2005
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?
Peter
The excellent Martelli Python Nutshell says that multiplication S*n is
"the concatenation of n copies of S" so S+S and S*2 would be expected to
be the same. It seems though that they are not but that * creates a list
Jiri Barton wrote:
> Hi everyone,
>
> 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
>
> []
>
> And, just to add to my confusion:
>
>
>>>>[[]]*2
>
> [[], []]
>
>>>>[[], []] == [[]]*2
>
> True
>
> Thanks in advance for the explanation.
> jbar
>
>
> BTW, if it matters...
> Python 2.4.1 (#2, Mar 30 2005, 20:41:35)
> [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
>
>
>
More information about the Python-list
mailing list