MattTheSnake MattTheSnake - 2 months ago 15
Python Question

Why is my list not getting reset on every loop in Python

I have a function that needs to take in a list called edges. I need to preform many loops and on each loop I change properties values of edges. At the beginning of the next loop I need edges to take on its original value. To try and deal with this I have cast my list as a tuple so it wouldn't be mutable and assigned it to permEdges. I then initialize trialEdges from permEdges so that I can make changes to trialEdges. The changes to trialEdges are staying around for the next loop and I don't know why.

If someone could explain why the output isn't consistent and how I can accomplish this goal of having the same list at the start of every loop I would be forever grateful :)

def randomMinCut(edges):
permEdges = tuple(edges)
tries = 3

for i in xrange(tries):
trialEdges = list(permEdges)
print trialEdges
trialEdges[0][0] = 100

return


sample input and output:

input:
[[1, 2], [1, 3], [1, 4], [1, 7]]
output:
[[1, 2], [1, 3], [1, 4], [1, 7]]
[[100, 2], [1, 3], [1, 4], [1, 7]]
[[100, 2], [1, 3], [1, 4], [1, 7]]


The first row is what I want repeated 3 times

Answer

permEdges may be a tuple, but its contents are not; remember that both permEdges and trialEdges are storing pointers to four two-element lists. When you set trialEdges[0][0] = 100, you're modifying but not replacing the first element of trialEdges, which is also the first element of permEdges.

There are several ways to achieve what you want, but copy.deepcopy is probably the best:

import copy

def randomMinCut(edges):
    tries = 3

    for i in xrange(tries):
        trialEdges = copy.deepcopy(edges)
        print trialEdges
        trialEdges[0][0] = 100

    return