0

I'm trying to copy a list to another list 6 times. I'm using:

for i in range(6):
   sides[i] = cubes.copy()

This makes a list with 6 copies of the cubes list, which should not be linked/should not refer to the same object, but be six different lists with the same content, but when I run the whole program (listed below), this seems to not be true. I included print statements in which the current value is printed, and it is obvious that one change affects all 6 lists for some reason.

This is the whole code:

def sideArray():
    cubes = [[-4,  8,  -4,   4,   16,  4],
             [-4, -4,  -2,   4,   8,   2],
             [-8, -4,  -2,  -4,   8,   2],
             [4,  -4,  -2,   8,   8,   2],
             [-4, -16, -2,   0,  -4,   2],
             [0,  -16, -2,   4,  -4,   2]]
    sides = [[], [], [], [], [], []]
    for i in range(6):
        sides[i] = cubes.copy()
    print(sides)
    print(sides[0] is cubes)
    for i in range(6):
        print()
        for j in range(6):
            if i < 3:
                sides[i][j][i] = cubes[j][i+3]
                print(f"sides[{i}][{j}][{i}] is now cubes[{j}][{i+3}] ({cubes[j][i+3]}).")
            else:
                sides[i][j][i] = cubes[j][i-3]
                print(f"sides[{i}][{j}][{i}] is now cubes[{j}][{i-3}] ({cubes[j][i-3]}).")
        print(f"is {sides[i]}")
        print(f"full: {sides}")
    return sides


if __name__ == '__main__':
    print(sideArray())

It is supposed to take every cube in the cubes list (defined by 2 corners) and make 6 lists inside the sides list, with each list being one side of the cube (e.g. if a cube was from 0, 0, 0, to 1, 1, 1 the first list would contain 1, 0, 0; 1, 1, 1, defining the left side of the cube.) If there is a better way to do this, please tell me.

Natan
  • 11
  • 4

2 Answers2

1

As suggested in the comments, copy() is what's known as a shallow copy. Nested structures still only references when shallow copied. In order to fully copy a nested data structure, you need to use deepcopy from the built-in copy module:

from copy import deepcopy

sides = [deepcopy(cubes) for _ in range(6)]
ddejohn
  • 8,775
  • 3
  • 17
  • 30
0

The issue is that all lists point to the same original list. Pass your list to python's built-in list() function to create new lists without referencing the original list.