-3

I decided to rewrite the question. This is a copied part of my script.

sp.append([cx,cy])
cx = 0
cy = 0

Before the cx = 0 and cy = 0, cx and cy were not 0, and sp was correct. but after setting cx and cy to 0, the appended list is [0,0] and not what cx and cy were before. How do I stop this from happening?

Glitch
  • 53
  • 6

2 Answers2

1

You need to copy the contents of a into your list so that you have a new list:

alist = []

a = [1,2]

alist.append(a[:])

a.clear()

print(alist)

Now the output is:

[[1, 2]]
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • I can't do this in my code, i would need to make hundreds of lists ahead of time so i can keep pushing the correct values back. It's hard to explain but I need to to get the value from the variable then not care what the variable is after. – Glitch Sep 28 '22 at 17:52
  • How was I supposed to be able to tell that from your question? Now you've changed your question to something equally unclear. You'll need to be much clearer. – quamrana Sep 28 '22 at 18:00
0

We can see what's happening if we get the id() of the lists:

test_list = []
print(id(test_list)) # output: 2280241512512

We have created a new list, called test_list, and its unique object id is shown above.

Now, we want to make a new list and add it into test_list. We'll call this list a, and get its id() which shows that it is a separate object:

a = [1,2]
print(id(a)) # output: 2280241515456

Once we've appended it to test_list, we can see that its contents are indeed there:

test_list.append(a)
print(test_list) # output: [[1, 2]]

So, if we loop through test_list, we can see the id() of the objects inside the list - and since we only added one item, a, we should expect to see its id there:

for item in test_list:
    print(id(item)) # output: 2280241515456

Indeed we do see the same id from earlier. So, we know the object a is referenced inside test_list. So, what happens if we clear a?

a.clear()
print(test_list) # output: [[]]

We have cleared out a, and since it is referenced inside test_list, we can see the change reflected. And if we get the id of the objects inside test_list, we can see that it's still the same object, a:

print(id(test_list[0])) # output: 2280241515456

But, what if we want a copy of a's data, rather than a itself, to go into test_list? There's multiple ways to go about it, but using the a[:] syntax is a quick shortcut.

test_list = []
a = [1,2]
print(id(a)) # output: 1707726818240
test_list.append(a[:])
print(test_list) # output: [[1, 2]]
for item in test_list:
    print(id(item)) # output: 1707729293952
a.clear()
print(a) # output: []
print(test_list) # output: [[1, 2]]

So, as we can see, using a[:] creates a copy of that list, and puts the copy into test_list, so that if we mess with a, the data in test_list is not affected.

Random Davis
  • 6,662
  • 4
  • 14
  • 24