List replication operator
Rob Gaddi
rgaddi at highlandtechnology.invalid
Thu May 24 14:24:41 EDT 2018
On 05/24/2018 11:17 AM, 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.
>
>
> Thoughts?
>
>
>
I think the same people making that mistake now would still do so
because they didn't know they needed the special operator.
[[] for _ in range(5)] works just as well without adding more syntax.
--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order. See above to fix.
More information about the Python-list
mailing list