0

When I try to copy a value stored in a list of list to another list of list, Spyder in Anaconda mistakenly assign the value to all lists of the first dimension.

Please see the code below.

I tried to print the value A[0][2] and self.image[2][0] before doing the assignment, they show the correct answer of 0 and 1. But when completing the task of assignment, the address of A[0][2] seems to be read in correctly as A[i][2] for all i.

class BImage(object):

    def __init__(self, image):
        self.image = image
        self.d1 = len(image)
        self.d2 = len(image[0]) if len(image) > 0 else 0

    # with a strange bug
    def transp_image(self):
        A = [[0]*self.d1] * self.d2
        for i in range(self.d2):
            for j in range(self.d1):
                # error:
                # when i == 0, j == 2, self.image[2][0] == 1
                # assign the value 1 to A[][2], instead of just A[0][2]
                A[i][j] = self.image[j][i]

        self.image = A
        k = self.d2
        self.d2 = self.d1
        self.d1 = k
bubble
  • 1,634
  • 12
  • 17
Benjamin
  • 93
  • 11

1 Answers1

1

Use a list comprehension to create your A variable.

Consider the following example:

lst = [ [float]*2 ]*3
lst[0][0] = 3.14
print(lst)
# [[3.14, <type 'float'>], [3.14, <type 'float'>], [3.14, <type 'float'>]]

lst = [ [float]*2 for _ in range(3) ]
lst[0][0] = 3.14
print(lst)
# [[3.14, <type 'float'>], [<type 'float'>, <type 'float'>], [<type 'float'>, <type 'float'>]]

I am sure there are plenty of answers in here who can explain how the first block creates three copies of the same object, whereas the second generates three unique objects.

Sigve Karolius
  • 1,356
  • 10
  • 26