List replication operator
MRAB
python at mrabarnett.plus.com
Thu May 24 16:02:23 EDT 2018
On 2018年05月24日 20:12, Ned Batchelder wrote:
> On 5/24/18 2:17 PM, Steven D'Aprano wrote:
>> 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.
>>Why "**"? Why not "@"?
[[]] @ 5
> "shallow" will be the next problem. Do we also need this?:
>> [[[]]]***5 # j/k
>I suppose the choice should be limited to 2 options: shallow copy and
deep copy.
More information about the Python-list
mailing list