-2

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?

1 Answers1

-1

A list is a type of object. This means that if you have a list, you can save it to multiple variables but if you change one, it will change all of them. If you want to make your list have separate sublists you can define it as shows_times = [[0 for y in range(4)] for x in range(4)]

Hippolippo
  • 803
  • 1
  • 5
  • 28