I was pulling my hair trying to fix a bug on some two dimensional list manipulations. The following script simply initializes a few empty lists, then does basic calculations and returns the output. The problem occurs when I call the main function, here is the code:
dataList=[]
outputList1=[]
outputList2=[]
fileData=["a","b","c"]
def initialize(*args):
global dataList
dataList=[[]for j in range(len(fileData))] #initialize the array with empty lists
for x in range(len(fileData)):
for y in range(12):
dataList[x].append(y) #populates the list with data
for x in args:
for y in range(len(fileData)):
x[1][2].append([]) #initializes the output lists with empty lists
def functionAdd(number, inputList, outputList):#basic data manipulation
for y in range(len(inputList)):
for x in range(len(inputList[y])):
outputList[y].append(inputList[y][x]+number)
def functionSubstract(number, inputList, outputList):#other basic manipulation
for y in range(len(inputList)):
for x in range(len(inputList[y])):
outputList.append(inputList[y][x]-number)
def mainFunction(*args):#unpacks the function names to be executed, as well as their arguments
for x in args:
x[0](*x[1])
f1=[functionAdd,(2,dataList,outputList1)]#variable of a function to be executed
f2=[functionSubstract,(3.5,dataList,outputList2)]#variable of a function to be executed
initialize(f1,f2)#this part works fine
mainFunction(f1,f2)#this part does't work
##mainFunction([functionAdd,(2,dataList,outputList1)],[functionSubstract,(3.5,dataList,outputList2)])
print(outputList1)
The initialization goes without issues with (initialize(f1,f2)), it unpacks the arguments and creates empty sub-lists in the corresponding list to make a 2-dimensional array.
However, when I try to call the "mainFunction" the same way, the print statement displays: [[], [], []], so basically no calculation has been done to it.
But, when I un-comment the last line and instead call the mainFunction in this way:
mainFunction([functionAdd,(2,dataList,outputList1)],[functionSubstract,(3.5,dataList,outputList2)])
then I get the correct output, and the print statement displays:
[[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]]
which is the correct result. So I finally got the function to work, but I still don't understand what's wrong with the previous syntax of calling it
mainFunction(f1,f2)
because in both cases I call the function with the exact same arguments...
Can anyone care to explain? Thanks,
dataList=from the initialise function and insertdataList.append([])afterfor x in range(len(fileData)):and it should do what you want.