[Tutor] Nested use of replication operator on lists

boB Stepp robertvstepp at gmail.com
Thu May 24 23:33:56 EDT 2018


On Python-list Steve started a thread, "List replication operator"
(https://mail.python.org/pipermail/python-list/2018-May/733513.html)
and wrote the following:

<quote>
Python has a sequence replication operator:

py> [1, 2]*3
[1, 2, 1, 2, 1, 2]


Unfortunately, it is prone to a common "gotcha":

py> x = [[]]*5  # make a multi-dimensional list
py> x
[[], [], [], [], []]
py> x[0].append(1)
py> x
[[1], [1], [1], [1], [1]]

The reason for this behaviour is that * does not copy the original list's
items, it simply replicates the references to the items. So we end up
with a new list containing five references to the same inner list.
</quote>

I am having trouble correlating the behavior of the one-dimensional
case with the two-dimensional case.  The result of [1, 2]*3 seems to
be an actual list, not a replication of the references to the items in
the original list, [1, 2].  Or if it is, then I do not know how to
demonstrate it.

Also the "replication operator" does not seem to be replicating
anything list-wise if it is instead replicating references to the
original list's members.

I request explanation/clarification please.


-- 
boB


More information about the Tutor mailing list