1

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

sygma_list [[]] * 3

and I have another lists having the form

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

When looping over the sygma_list I have like so:

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

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

sygma_list = [[[1,2,3], [1,2,3]],
              [[4,5,6],[4,5,6]],
              [[6,7,8],[6,7,8]]]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

1 Answers1

3

The biggest catch in your code is this: When you do this:

sygma_list = [[]] * 3

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

Do this instead:

sygma_list = [list() for x in range(3)]

That will create 3 distinct lists.

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

Let's consider this fixed 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)

yields:

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

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

sygma_list[i].extend(mts_column[i])

would make a list of lists instead of making a list of lists of lists

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • I suppose that's because the question is not clear about what the "suprising" result is and adds to the confusion. I get a different expected result. I have edited my post. The duplication of the internal list array is the main point. – Jean-François Fabre Sep 15 '16 at 14:22
  • It is still downvoted (+3/-1) but got 3 upvotes afterwards so some people made it up to the answer which gives the root cause. thanks for that. maybe the whole thing (question+answer) wasn't clear, that's all. I've got a particular love for that problem since I had it myself when doing wrongly: `[MyObject()] * 10` some time ago. – Jean-François Fabre Sep 15 '16 at 14:24