0

I try to generate a multi dimensional list depending on two variables: size and dim. Both of them are initialized with user input, so I don't know their values while coding. An example with dim = 3 and size = 2 would be: [[['+', '+'], ['+', '+']], [['+', '+'], ['+', '+']]]. What I have tried so far:

import copy
fields = '+'
for i in range(dim):
    fields = [copy.copy(fields) for j in range(size)]

While this works totally fine for dim in [1, 2], it only creates references to the same list if dim > 2. Example with size = 3 and dim = 3:

>>> f
[[['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']], [['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']], [['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']]]
>>> f[0][0][0] = 'X'
>>> f
[[['X', '+', '+'], ['+', '+', '+'], ['+', '+', '+']], [['X', '+', '+'], ['+', '+', '+'], ['+', '+', '+']], [['X', '+', '+'], ['+', '+', '+'], ['+', '+', '+']]]

I know this behavior from code like f = [[['+'] * 3] * 3] * 3 and thought I could prevent it with copy.copy(), but this obviously doesn't work. I tried this with Python 3.2.2 on android (QPython 3) and with Python 2.7 on Windows, I got the same results. Please note that I don't want to use a non-standard library like numpy.

2 Answers 2

2

You can use the copy.deepcopy(). the copy.copy() is just shallowcopy.

the difference between these two methods:

the difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Sign up to request clarification or add additional context in comments.

Comments

0

I would use numpy arrays for this giving more convenient slicing and indexing operations. Also allows for more dimensions than 2-3 and cleaner code.

import numpy as np
X = np.empty((width, height), dtype=object)

Then you can fill it via your desired method, e.g:

import itertools
for x, y in itertools.product(range(width), range(height)):
     X[x, y] = '+'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.