I'm solving this challenge on HackerRank in Python 3 and came up with the following solution:
def dynamicArray(n, queries):
seqList = [[] for _ in range(n)]
lastAnswer = 0
result = []
for query in queries:
if query[0] == 1:
seqList[(query[1] ^ lastAnswer) % n].append(query[2])
elif query[0] == 2:
seq = seqList[(query[1] ^ lastAnswer) % n]
lastAnswer = seq[query[2] % len(seq)]
result.append(lastAnswer)
return result
This works fine and passes all test cases.
The problem is when i change the initialization of seqList
from the following:
seqList = [[] for _ in range(n)]
To this:
seqList = [[]] * n
Then all test cases fail and i cannot figure out why. There are no other changes in the code.
I've even created the following simple test case just to compare the results of these initialization methods:
n = 3
a1 = [[]] * n
a2 = [[] for _ in range(n)]
print(a1)
print(a2)
print(a1 == a2)
And the result is as expected:
[[], [], []]
[[], [], []]
True
I'd really appreciate if someone could explain this behavior to me.