BnnBonnie
BnnBonnie

Reputation: 31

How can I save the value of a variable in a list but not the variable itself?

My problem is that when I append a variable to a list in python, it saves the pointer to the value in the list and not the value itself. This means that when I change the variable that I appended to the list, the value in the list changes as well which I don't want. I want to save the current value of the variable in the moment I append it to the list, and that shall not change anymore after the appending.

Here is the code, I hope I could make myself clear:

while j < n:
    if first_graph[j] == (n-1):
        while first_graph[j] == (n-1) and j < n-1:
            j += 1
        if first_graph[j] == (n-1) and j == n-1:
            j += 1
        else:
            first_graph[j] += 1
            for i in range(j):
                first_graph[i] = 0
            all_graphs.append(first_graph)
            j = 0
    else:
        first_graph[j] += 1
        all_graphs.append(first_graph)

This is obviously not all of it, but my problem is that the first_graph in the all_graphs list gets updated when it changes, so in the end all_graphs is just filled with the same list several times

Upvotes: 0

Views: 742

Answers (1)

M Z
M Z

Reputation: 4799

Make a copy of the list:

all_graphs.append(list(first_graph))

Upvotes: 1

Related Questions