linked list output not expected in Python 2.7
<p>Implement a linked list and I expect output to be <code>0, -1, -2, -3, ... etc.</code>, but it is <code>-98, -98, -98, -98, ... etc.</code>, wondering what is wrong in my code? Thanks.</p>

<pre><code>MAXSIZE = 100
freeListHead = None

class StackNode:
    def __init__(self, value, nextNode):
        self.value = value
        self.nextNode = nextNode

if __name__ == "__main__":
    # initialization for nodes and link them to be a free list
    nodes=[StackNode(-1, None)] * MAXSIZE
    freeListHead = nodes[0]
    for i in range(0, len(nodes)-1):
        nodes[i].nextNode = nodes[i+1]
        nodes[i].value = -i
    for node in nodes:
        # output -98, -98, -98, -98, ... etc.
        # exepcted output, 0, -1, -2, -3, ... etc.
        print node.value
</code></pre>

<p>This is the problem:</p>

<pre class="lang-py prettyprint-override"><code># initialization for nodes and link them to be a free list
nodes=[StackNode(-1, None)] * MAXSIZE
</code></pre>

<p>When you use the multiply operator, it will create multiple <em>references</em> to the <strong>same</strong> object, as noted <a href="http://stackoverflow.com/a/2785963/895932">in this StackOverflow answer</a>. So changing one node's value (as in <code>nodes[i].value = -i</code>) will affect every node since every item in the list points to the same object.</p>

<p>In that same linked answer, the solution is to use <a class='doc-link' href="http://stackoverflow.com/documentation/python/5265/list-comprehensions#t=201609260515199970598&amp;a=syntax">list comprehension</a>, like this:</p>

<pre class="lang-py prettyprint-override"><code>nodes = [StackNode(-1, None) for i in range(MAXSIZE)]
</code></pre>

<p>Also, note that you did not set the value of the last element, so the output (after the fix I suggested above) will be:</p>

<pre>
0, -1, -2, ..., -98, -1
</pre>

python python-2.7