List replication operator

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri May 25 02:48:09 EDT 2018


On Fri, 25 May 2018 15:30:36 +1000, Cameron Simpson wrote:

> So, how to various forms of multidimensional lists play out as code?

With my suggestion, we get:

x = [0]**3  # one-dimensional
y = [[0]**3]**3  # two-dimensional
z = [[[0]**3]**3]**3  # three-dimensional

Or there's MRAB's suggestion of using @ instead of the ** operator.

The one-dimensional case can be optimized by using regular * replication
instead of ** duplication, but that's an optimization for immutable
objects. Its pretty much harmless to write ** instead of * for the common 
case of a list filled with immutable ints or None.



Here's a subclass that implements a simple version of this for testing:

class ML(list):
    def __pow__(self, other):
        import copy
        L = []
        for i in range(other):
            L.extend(copy.deepcopy(obj) for obj in self)
        return ML(L)


And in use to generate a 3-D list:

py> z = ML([ML([ML([0])**3])**3])**3
py> z[0][0][0] = 1
py> z[1][1][1] = 2
py> z[2][2][2] = 3
py> z
[[[1, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 2, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 3]]]


The repeated calls to ML() are ugly and are only there because the []
syntax creates ordinary lists, not my subclass.



-- 
Steve




More information about the Python-list mailing list