0

Having a class C with an attribute coordinates.

class C():
   def __init__():
      self.coordinates=[]

c = C()
coords = c.coordinates

if I change now coords, I would like to change it only "local", so I would like to detach coords from C, so that c.coordinates isn't changed.

Is there a better way than

coords_ = coords[:]
nuemlouno
  • 288
  • 1
  • 10
  • 3
    Just to be clear, this has nothing to do with classes and attributes. This is how references to *any* list works. `a = []; b = a` has the same effect. – Mark Jan 19 '22 at 00:29
  • 4
    `coords = coords[:]` is how I'd write it (no need to create a new variable name). `coords = coords.copy()` might be a bit clearer. – jasonharper Jan 19 '22 at 00:31
  • Using `coords[:]` is the simplest way to make a copy of the list. – martineau Jan 19 '22 at 00:33
  • beware that `coords[:]` makes a shallow copy of `coords` – jkr Jan 19 '22 at 01:41

0 Answers0