0

Sorry, I'm not sure how to properly called this given situation:

O = [[255, 0], [0, 255]]
clone = [O[0],O[1],O[0],O[1]]
print ("clone="+str(clone))
clone[0].insert(0, 99)
print ("clone="+str(clone))

Because variable clone have 2 instance of variable O, and its been repeated twice, later on when I change one instance of this the other part will also be changed, is there a way to make the cloned version be "baked down" and not as an instance? would like to explore ways to do this during on first first step when its cloned on line 2 of the example, or after the clone at the end, because my code is dealing with thousands of these types of clones, the speed will matter, Thanks a lot for any help in advanced!

1 Answers1

1

You can clone each list in an iterable rather easily manually:

O = [[255, 0], [0, 255]]
clone = [O[0],O[1],O[0],O[1]]
clone = [x[:] for x in clone]
print ("clone="+str(clone))
clone[0].insert(0, 99)
print ("clone="+str(clone))

Or just do that to begin with:

O = [[255, 0], [0, 255]]
clone = [O[0][:],O[1][:],O[0][:],O[1][:]]
print ("clone="+str(clone))
clone[0].insert(0, 99)
print ("clone="+str(clone))

You can also not mutate the list:

O = [[255, 0], [0, 255]]
clone = [O[0],O[1],O[0],O[1]]
print ("clone="+str(clone))
clone[0] = [99] + clone[0]
print ("clone="+str(clone))
Ry-
  • 218,210
  • 55
  • 464
  • 476