0

I have a small question regarding python as I am a java developer

Consider this piece of code

testMap = {}
i = 2
for t in range(3):
    tempArr = [i, i * i]
    tempArr2 = [i + 1, i + 2]
    testMap[i] = tuple((tempArr, tempArr2))
    i += 1
print(testMap)

output: {2: ([2, 4], [3, 4]), 3: ([3, 9], [4, 5]), 4: ([4, 16], [5, 6])}

tempArr is a type of List here so, as lists are mutable so assigning a new list in the next iteration to variable tempArr creates a new OBJECT and does not change the value of the same variable created in the first iteration, why?

I mean to say assigning new values every iteration to the same variable should change all the previous elements in the testMap but this is not the case, any explanation around this will be helpful

Like If I use the tempArr from map like

arr = testMap[2]
arr[0] = "56"

The above code modified the list, but in the for loop the thing is different.

abstractnature
  • 466
  • 2
  • 9

0 Answers0