List replication operator

Ben Bacarisse ben.usenet at bsb.me.uk
Fri May 25 06:48:49 EDT 2018


Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:

> On Thu, 24 May 2018 16:05:32 -0700, Paul wrote:
>
>> How would one make a multi-dimensional list now, with truly-separate sub
>> lists?  Is there just no way to do it with the replication operator?
>
> Correct. Let's say you want to make a 1-D list with three items 
> initialised to zero. This works brilliantly:
>
> py> [0]*3
> [0, 0, 0]
>
> This seems like it ought to create a 3x3 2-D list:
>
> py> y = [[0]*3]*3
> py> y
> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>
>
> but alas, it's a trap:
>
> py> y[0][0] = 1
> py> y
> [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Another way of looking at it would be in terms of evaluation rather than
copying.  [<stuff>] evaluates to a new list object, so if there were an
alternate version of L * n (for the sake of argument L ** n) that
evaluated the list expression n times to make the new list you would
also get the behaviour you want.

You would also be able to use it in situations like this:

  import random
  [random.randint(1,10)]**6

to get (for example) [2, 4, 7, 1, 1, 8].

Of course, this is just what the [L for _ in range(n)] solution does,
but maybe the situation merits a shorthand?

<snip>
-- 
Ben.



More information about the Python-list mailing list