[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

List replication operator

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 


would return a new list consisting of five shallow copies of the inner