Might be a naive question but this troubled me a lot. I want to initialize a list with some default values. I consider the following 2 approaches to do so:
1.cache1 = [[-1 for _ in range(5)] for _ in range(5)]
2. cache2 = [[-1]*5]*]
I was under the assumption that their behavior is exactly the same. However, when I execute the following commands:
cache1[0][0] = 100
cache2[0][0] = 100
The lists are updated to:
cache1 = [[100, -1, -1, -1, -1], [100, -1, -1, -1, -1], [100, -1, -1, -1, -1], [100, -1, -1, -1, -1], [100, -1, -1, -1, -1]]
cache2 = [[100, -1, -1, -1, -1], [100, -1, -1, -1, -1], [100, -1, -1, -1, -1], [100, -1, -1, -1, -1], [100, -1, -1, -1, -1]]
Can someone please point out what is the difference between the two initializations? Thank you