'Python: list.remove() behave wiredly [closed]

def get_variables(cells):
    domains = [1,2,3,4]
    variables = {}
    for cell in cells:
        if(cell == "C11"):
            variables[cell] = [1]
        elif(cell == "C22"):
            variables[cell] = [2]
        elif(cell == "C33"):
            variables[cell] = [3]
        elif(cell == "C44"):
            variables[cell] = [4]
        else:
            variables[cell] = domains

cells = ['C'+x+y for x in "1234" for y in "1234"]
variables = get_variables(cells)
csp = CSP(variables, constraints, assigned)
pprint(csp.variables)
csp.variables["C12"].remove(1)
print(csp.variables["C13"])
output: 
{'C11': [1],
 'C12': [1, 2, 3, 4],
 'C13': [1, 2, 3, 4],
 'C14': [1, 2, 3, 4],
 'C21': [1, 2, 3, 4],
 'C22': [2],
 'C23': [1, 2, 3, 4],
 'C24': [1, 2, 3, 4],
 'C31': [1, 2, 3, 4],
 'C32': [1, 2, 3, 4],
 'C33': [3],
 'C34': [1, 2, 3, 4],
 'C41': [1, 2, 3, 4],
 'C42': [1, 2, 3, 4],
 'C43': [1, 2, 3, 4],
 'C44': [4]}
[2, 3, 4]

It is supposed to remove 1 from "C12", instead it did it to "C13". Why is that? I guess something related to memory location? This really drives me crazy. Any suggestion would be appreciated!



Solution 1:[1]

I suppose that "C12" and "C13" don't contain different lists, but the same one. Meaning that no matter how you modify either one, the other will be affected in the same way.

To see this clearly, print csp.variables at the end instead of just "CSP12".

The mistake is this line:

variables[cell] = domains

Because every variable[cell] is given the same list. Which is a mutable type. So when it is modified, it will be modified in place.

To fix this you could give the cells copies or slices, which are different objects:

variables[cell] = domains.copy()

or

variables[cell] = domains[:]

Solution 2:[2]

try this

desired_key = 'C12'
for key in csp.keys():
  if key == desired_key:
    del csp[key][0]


print(csp)
``

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2 Jewel_R