0

I am trying to append 5 cells to "completeArray" while with each call of the function incrementing the originArray[x][1] by 1 increment. however the answer is always a duplicate!

originArray = [[0,0],[0,1],[1,0],[2,0],[3,0]]
completeArray = []

def myFuncTest():
    tempArray = []
    for cell in originArray:
        tempArray.append(cell)
        
    completeArray.extend(tempArray)
    tempArray = []
    
    for cell in originArray:
         cell[1] = cell[1]+1
    print("++--",originArray)
            
    return completeArray
            
print("----",myFuncTest())
print("----",myFuncTest())

The result is

++-- [[0, 1], [0, 2], [1, 1], [2, 1], [3, 1]]
---- [[0, 1], [0, 2], [1, 1], [2, 1], [3, 1]]
++-- [[0, 2], [0, 3], [1, 2], [2, 2], [3, 2]]
---- [[0, 2], [0, 3], [1, 2], [2, 2], [3, 2], [0, 2], [0, 3], [1, 2], [2, 2], [3, 2]]

The correct result of "completeArray" should be as follows

[[0, 1], [0, 2], [1, 1], [2, 1], [3, 1], [0, 2], [0, 3], [1, 2], [2, 2], [3, 2]]
  • because your `completeArray` is out of scope of the function so it will keep the value after the function ran 1 time, when you call the second time with `extends` you basically add new elements from `originArray` to updated `completeArray` after the first run of the function. For the `originArray` the same thing happened, your +1 affected the second time you ran the function that why the value in tuple got +1 – Linh Nguyen Feb 10 '22 at 09:41
  • Can you simplify what is wrong with an example, i didn't understand, what should be the fix for the case here? – Zubair Al-Shehhi Feb 10 '22 at 10:00

0 Answers0