I am having some trouble with the following script. It should make 3 copies of the following list so that they can be modified independently. However, it seems to be creating 3 clones of the same list, and when you modify one you modify them all. Here is the function:
def calculateProportions(strategies,proportions):
import itertools
combinations = []
columns = list(itertools.product(strategies,repeat=3))
for i in range(0,len(columns)):
columns[i] = list(columns[i])
for n in range(0,len(strategies)):
combinations.append(columns[:])
combinations[0][0][0] = "THIS SHOULD ONLY BE IN ONE PLACE"
print combinations
strategies = [[0,0],[0,50],[50,50]]
calculateProportions(strategies,[])
Notice how, when you run this, you see the string “THIS SHOULD BE IN ONE PLACE” 3 times (position [0][0][0],[1][0][0], and [2][0][0], not once. This appears to be because the lists are aliased together rather than cloned. However I explicitly cloned it.
I have spent the last hour banging my head into the table on this. Your suggested solutions are much appreciated!
You’re only performing a shallow copy when you clone
columns, i.e. the list is cloned but its items are not, so the same item references are used in bothcombinationsandcolumns.You can use the copy.deepcopy() function to perform a deep copy of the object:
Or, more simply, a list comprehension: