0

I have a very basic question, although I searched the web I couldn't come up with an alternative. I have found similiar topics on this but it just didn't seem to work for me. The goal: I want to add a changing list element into a list. I know extend can make a list values go into one list; but I want them stored as lists not as values inside a list. What I have tried: I have tried appending each changed item I have to a bigger list. Homever, when the appended item changes so does the bigger list,which is not I want.

The problems with it:

The result I want from the code:

tobesent=[[1,0,0,1,22],[1,0,0,11,33]]

The result I get from the code:

tobesent=[[1, 0, 0, 11, 33], [1, 0, 0, 11, 33]]

When I used debugger to understand the problem when the item changes to become the second item, the first item also changes. I don't want this.

What I have tried:

I have tried adding the list elements one by one using the append function of a list. However, I have also tried the extent function to see if the values come up right and there was nothing wrong with that. On the other hand, they are just stored as values and not as lists.

The final code I have at hand:

Here is what I have tried.

tobesent=[]
output=[]
anotherlist=[1,22,11,33]

biglist=[1,0,0,0,0]
for i in range(0,len(anotherlist),2):
    biglist[3]=anotherlist[i]
    biglist[4]=anotherlist[i+1]
    print(biglist)
    tobesent.append(biglist)
    print(tobesent)
Batselot
  • 194
  • 10
  • 1
    `tobesent.append(biglist[:])` to avoid the alias. – ggorlen Apr 20 '20 at 00:10
  • 1
    This comes up very often on SO, please look a bit more - also this https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – Grismar Apr 20 '20 at 00:10
  • This is a great link and the advice @ggorlen provided me with did the job. Thanks a lot for your comments – Batselot Apr 20 '20 at 00:13
  • 1
    ah.. someone else beat me to it.. yes.. use `biglist[:]` to generate a copy of the list - that way you're not appending an object reference of the same list each time. – Todd Apr 20 '20 at 00:13

0 Answers0