0

I am working on a graph coloring problem. Right now I'm stuck on a step that should be very simple. I've created a dictionary that includes all possible colors for each node (different colors are represented by the integers 0, 1, 2 ,3). See below. (Apologies in advance if the formatting of the question doesn't come out correctly. This is my first time asking a question here).

        node_count = 4
        colors = [0,1,2,3]

        sol_dict = {node:colors for node in range(0,node_count)}

        print(sol_dict)

Output:

        {0: [0, 1, 2, 3], 1: [0, 1, 2, 3], 2: [0, 1, 2, 3], 3: [0, 1, 2, 3]}

All I want to do is remove elements from some of these lists when I apply a constraint. For instance, if my algorithm discovers that node 1 in the dictionary cannot take the color value 0, I want to remove 0 from the list associated with the dictionary key 1. To do this I write:

        sol_dict[1].remove(0)

        print(sol_dict)

Output:

        {0: [1, 2, 3], 1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}

As you can see, this removes 0 from all items in the dictionary. I am at a loss to why this is happening. Let me know what you think. I've been stuck on this a while.

lcleary
  • 65
  • 6
  • If you take the same `colors` each time you end upwith 4 references to the same `colors` object. `sol_dict = {node:colors.copy() for node in range(0,node_count)}` creates a new object for each of your dict entries. – Finn Jan 07 '21 at 15:17
  • [This](https://stackoverflow.com/questions/13538266/python-copy-of-a-variable) explains it for variables. [This](https://stackoverflow.com/q/986006/5124383) is the full story if you are interested – Finn Jan 07 '21 at 15:20
  • I see. I assumed that once the dictionary was created it would make a new object each time. I didn't realize it would refer back to the original object. Thanks for your help. – lcleary Jan 07 '21 at 15:28
  • [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html) – wwii Jan 07 '21 at 16:42

0 Answers0