I have a class that has a list as one of its attributes:
class Hello(object):
stuff
self.List = [True, False, True False]
I want to pass a copy of that list into a tuple so I can change the list while referring back to previous copies of the list. I do the following:
def getStartState(self):
copiedList = copy.deepcopy(self.cornerList)
fullState = (self.startingPosition[0], self.startingPosition[1], tuple(copiedList))
return fullState
I am getting an error telling me that copy is not a global variable. Am I missing something?
I think there are a few issues here.
First off, your error is probably because you are not importing the
copymodule. That is an easy fix. Just atimport copyat the top of your file.The second issue is that there’s no need to
deepcopya list of immutable objects likebools. Since the list’s members can’t be changed in place, any ofcopy.copy(List),list(List)orList[:]will work just fine. Deep copying is only necessary if there are nested mutable structures.Finally, there’s no need to copy a list just to make a tuple out of the copy. Tuple’s are immutable and don’t modify their source sequence, so you can make your
getStartStatemethod simpler: