Why is my list not getting reset on every loop in Python
<p>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. </p>

<p>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 :)</p>

<pre><code>def randomMinCut(edges):
    permEdges = tuple(edges)
    tries = 3

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

    return
</code></pre>

<p>sample input and output:</p>

<pre><code>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]]
</code></pre>

<p>The first row is what I want repeated 3 times</p>

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

<p>There are several ways to achieve what you want, but <a href="https://docs.python.org/2/library/copy.html" rel="nofollow"><code>copy.deepcopy</code></a> is probably the best:</p>

<pre><code>import copy

def randomMinCut(edges):
    tries = 3

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

    return
</code></pre>

python list tuples