List replication operator
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu May 24 14:17:20 EDT 2018
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.
This is not a bug and changing the behaviour is not an option.
But what do people think about proposing a new list replication with copy
operator?
[[]]**5
would return a new list consisting of five shallow copies of the inner
list.
Thoughts?
--
Steve
More information about the Python-list
mailing list