Ad

Create A List That Every Step Add Some Element Itself (without Replacing Them)

- 1 answer

i have this problem: there are 4 variables, each variable can have a value:{0, 1, 2, 3}. So i can represent it with a list of list (each raw shows the possible value of each variable):

[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3]

In my program at every step i reduce the possible values, for example at step 1 i can get:

[0, 1]
[2, 3]
[1, 3]
[1, 2]

So i'd like keep track of all changes. I'm thinking to create a second list with the story of every variable (to go back in case of error). Something like this:

[0, 1, 2, 3],[0, 1]
[0, 1, 2, 3],[2, 3]
[0, 1, 2, 3],[1, 3]
[0, 1, 2, 3],[1, 2]

At step 1 no problem , i use append() function and all is ok. In the the next steps though append function does not continue to add items to each line but replaces those already inserted. For example at step 2 instead of doing this:

[0, 1, 2, 3],[0, 1],[1] 
[0, 1, 2, 3],[2, 3],[3] 
[0, 1, 2, 3],[1, 3],[3] 
[0, 1, 2, 3],[1, 2],[2] 

it does this:

[0, 1, 2, 3],[1] 
[0, 1, 2, 3],[3] 
[0, 1, 2, 3],[3] 
[0, 1, 2, 3],[2] 

How can I solve?

Ad

Answer

You have to use a copy of the list. Make a copy and remove elements from the copied list, then append to the original list accordingly. To make a copy,

editableList = mainList[:]
Ad
source: stackoverflow.com
Ad