don't understand python's behaviour of three dimensional lists (references to sublists are the same)
<p>I don't understand why the following code behaves the way it does.    </p>

<pre><code>import numpy as np


nbr_arrays = 4
nbr_fields_per_array = 3
nbr_subfields_per_field = 2

# pre-allocate zeros list
zeros = np.zeros(nbr_subfields_per_field)

data = []
for array in range(nbr_arrays):

    # pre-allocate the subarray 
    empty_array = []
    for empty_array_index in range(nbr_fields_per_array):
        empty_array.append(zeros)

    # append pre subarray to data
    data.append(empty_array)

    # fill up data
    for j in range(nbr_fields_per_array):
        for k in range(nbr_subfields_per_field):
            data[array][j][k] = j*k*array
</code></pre>

<p>The generated output <code>data</code> reads now:</p>

<pre><code>[[array([ 0.,  6.]), array([ 0.,  6.]), array([ 0.,  6.])],
 [array([ 0.,  6.]), array([ 0.,  6.]), array([ 0.,  6.])],
 [array([ 0.,  6.]), array([ 0.,  6.]), array([ 0.,  6.])],
 [array([ 0.,  6.]), array([ 0.,  6.]), array([ 0.,  6.])]]
</code></pre>

<p>Even <code>zeros</code> reads completely differently:</p>

<pre><code>array([ 0.,  6.])
</code></pre>

<p>If I look at the identify of the different lists, this is what I get:</p>

<pre><code>id(data[0][0])
Out[72]: 45790208

id(data[1][0])
Out[66]: 45790208

id(data[2][0])
Out[67]: 45790208

id(data[3][0])
Out[68]: 45790208

id(zeros)
Out[69]: 45790208
</code></pre>

<p>why are all the references the same? and why does <code>zero</code> suddenly contain non-zero values?</p>

<p>I'd really appreciate it if somebody <strong>could explain me what exactly is happening here</strong>, and <strong>how I have to modify my code to see the expected behaviour</strong> (output).</p>

<p><strong>EDIT:</strong></p>

<p>not using <code>zeros</code> but using <code>[[0]*nbr_subfields_per_field for x in range(nbr_fields_per_array)]</code> instead gives me the expected result. but why? why doesn't the original code work?
Modified code that works:</p>

<pre><code>data = []
for array in range(nbr_arrays):
    empty_array = [[0]*nbr_subfields_per_field for x in range(nbr_fields_per_array)]

    ''' this is causing the weird behaviour 
    empty_array = []
    for empty_array_index in range(nbr_fields_per_array):
        empty_array.append(zeros)
    '''

    data.append(empty_array)

    for j in range(nbr_fields_per_array):
        for k in range(nbr_subfields_per_field):
            data[array][j][k] = j*k*array
</code></pre>
