-2

I am trying to add a number of list to a list and later I want to modify the values. Somehow all lists added at once seem to be linked.

data=[]

def data_extend(multiples):    
    a=["NV"]*2
    for i in range(multiples):
        data.append(a)
        
data_extend(2)
print(data)

data[0][1]=5
print(data)

the output is:

[['NV', 'NV'], ['NV', 'NV']]
[['NV', 5], ['NV', 5]]

I expected:

[['NV', 'NV'], ['NV', 'NV']]
[['NV', 5], ['NV', 'NV']]

Why is it like this?

Spynx
  • 33
  • 7

1 Answers1

1

Since you defined the a object before for loop, both of the items are the same object. If you only want one to change, you should do this:

data=[]

def data_extend(multiples):    
    for i in range(multiples):
        a=["NV"]*2
        data.append(a)
        
data_extend(2)
print(data)

data[0][1]=5
print(data)

Thus, all items of the list will be different items.