Appending a list into a list of lists in python
<p>I am trying to create and append a list and index in a list. Appending any list element is being automatically appended to all the lists available in this list
First of all I have a list as following</p>

<pre><code>sygma_list [[]] * 3
</code></pre>

<p>and I have another lists having the form</p>

<pre><code>mts_columns1 = [[1,2,3], [4,5,6], [6,7,8]]
mts_columns2 = [[1,2,3], [4,5,6], [6,7,8]]
</code></pre>

<p>When looping over the sygma_list I have like so:</p>

<pre><code> for i in range(0, 3):
       sygma_list[i].append(mts_column[i])
</code></pre>

<p>the results of sygma_list are being quite shocking, as append() is behaving on each element of the list instead of obtaining a final result of</p>

<pre><code>sygma_list = [[[1,2,3], [1,2,3]],
              [[4,5,6],[4,5,6]],
              [[6,7,8],[6,7,8]]]
</code></pre>

<p>The biggest catch in your code is this: When you do this:</p>

<pre><code>sygma_list = [[]] * 3
</code></pre>

<p>you create a size-3 array of references on the same list: not that you generally want and certainly not here</p>

<p>Do this instead:</p>

<pre><code>sygma_list = [list() for x in range(3)]
</code></pre>

<p>That will create 3 distinct lists.</p>

<p>(this construct is OK for immutable objects like [0]*3 or["foo"]*4)</p>

<p>Let's consider this fixed code:</p>

<pre><code>sygma_list = [list() for _ in range(3)]

mts_column = [[1,2,3], [4,5,6], [6,7,8]]

for i in range(0, 3):
    sygma_list[i].append(mts_column[i])

print(sygma_list)
</code></pre>

<p>yields:</p>

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

<p>BTW: Not sure if you want to append or extend your list (flatten it or not)</p>

<pre><code>sygma_list[i].extend(mts_column[i])
</code></pre>

<p>would make a list of lists instead of making a list of lists of lists</p>

python list append