-1
I = [[140,50],[140,80],[140,110],[140,140]]
O = [[140,50],[170,50],[140,80],[170,80]]

tomato = [I,O]


class Change():
    def __init__(self,):
        self.liste = []
    
def change(self,):
    self.liste.extend(tomato[0])
    for i in range(10):
        self.liste[0][0] += 10

That class when ı use change method this changing global tomato[0] how can i fix that.

  • You are storing a _reference_ to `tomato` in `liste`. So when you change one element in the latter, it changes in the former as well – gimix Aug 18 '22 at 08:31
  • 1
    Does this answer your question? [How do I clone a list so that it doesn't change unexpectedly after assignment?](https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment) – SuperStormer Aug 18 '22 at 08:36

1 Answers1

0

Here is a simplified example illustrating your problem.

Initialize a list object x:

x = [0]

Initialize another list a, storing the previous list x in it as an element:

a = [x]

Initialize yet another list b and add the elements from a to it; the only element in a is the list object x, which is now appended to b:

b = []
b.extend(a)

This means that the first (and only) element in b is that same list object x; not a clone, not another list with its elements, but that exact same object:

print(b[0] is x) 

Gives True.

Notice that I did not check equality, but identity using is.

This means I can write

b[0][0] = 1
print(x[0] == 1)

and get True.

Your code is a great example of why it is usually a terrible idea to muck around with global variables.

Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41