I am trying to create a list of lists, and want to update only a particular sublist by indexing, but when i try to do it via the following approach, all other sublist's also get updated.
times=[0]*4
shows_times=[]
for i in range(4):
shows_times.append(times)
shows_times[0][0]+=1
shows_times[0][1]+=1
shows_times[0][2]+=1
print(shows_times)
Output:
[[1, 1, 1, 0], [1, 1, 1, 0], [1, 1, 1, 0], [1, 1, 1, 0]]
But when i use the following code, i get the desired output.
shows_times=[]
for i in range(4):
shows_times.append([0,0,0,0])
shows_times[0][0]+=1
shows_times[0][1]+=1
shows_times[0][2]+=1
print(shows_times)
Output:
[[1, 1, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Please explain me why this behavior happens, has this anything to do with pass by value or pass by reference or something like that?