List replication operator
Ned Batchelder
ned at nedbatchelder.com
Thu May 24 15:12:09 EDT 2018
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.
>
"shallow" will be the next problem. Do we also need this?:
[[[]]]***5 # j/k
--Ned.
More information about the Python-list
mailing list