简体   繁体   中英

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

Make a copy of the list:

all_graphs.append(list(first_graph))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM