python changes values of list
<p>I am fairly new to Python so please be patient, this is probably simple. I am trying to build an adjacency list representation of a graph. In this particular representation I decided to use list of lists where the first value of each sublist represents the tail node and all other values represent head nodes. For example, the graph with edges <code>1-&gt;2, 2-&gt;3, 3-&gt;1, 1-&gt;3</code> will be represented as <code>[[1,2,3],[2,3],[3,1]]</code>.</p>

<p>Running the following code on this edge list, gives a problem I do not understand.</p>

<p>The edge list (<code>Example.txt</code>):</p>

<pre><code>1 2
2 3
3 1
3 4
5 4
6 4
8 6
6 7
7 8
</code></pre>

<p>The Code:</p>

<pre><code>def adjacency_list(graph):

graph_copy = graph[:]
g_tmp = []
nodes = []
for arc in graph_copy:

    choice_flag_1 = arc[0] not in nodes
    choice_flag_2 = arc[1] not in nodes
    if choice_flag_1:
        g_tmp.append(arc)
        nodes.append(arc[0])
    else:
        idx = [item[0] for item in g_tmp].index(arc[0])
        g_tmp[idx].append(arc[1])

    if choice_flag_2:
        g_tmp.append([arc[1]])
        nodes.append(arc[1])

return g_tmp


# Read input from file
g = []
with open('Example.txt') as f:
    for line in f:
        line_split = line.split()
        new_line = []
        for element in line_split:
            new_line.append(int(element))
        g.append(new_line)
print('File Read. There are: %i items.' % len(g))
graph = adjacency_list(g)
</code></pre>

<p>During runtime, when the code processes arc <code>6 7</code> (second to last line in file), the following lines (found in the <code>else</code> statement) append <code>7</code> <strong>not only</strong> to <code>g_tmp</code> <strong>but also</strong> to <code>graph_copy</code> and <code>graph</code>.</p>

<pre><code>idx = [item[0] for item in g_tmp].index(arc[0])
g_tmp[idx].append(arc[1])
</code></pre>

<p>What is happening?</p>

<p>Thank you!</p>

<p>J</p>

<p>P.S. I'm running Python 3.5</p>

<p>P.P.S. I also tried replacing <code>graph_copy = graph[:]</code> with <code>graph_copy = list(graph)</code>. Same behavior.</p>

<p>The problem is in the lines</p>

<pre><code>   if choice_flag_1:
       g_tmp.append(arc)
</code></pre>

<p>When you append arc, you are appending a shallow copy of the inner list. Replace with a new list like so</p>

<pre><code>   if choice_flag_1:
      g_tmp.append([arc[0],arc[1]])
</code></pre>

python list graph