Home > database >  I am clearing one list but it clears another list also
I am clearing one list but it clears another list also

Time:04-02


a = []

b = ['abc']
a.append(b)
print(a)

b.clear()

b = ['xyz']
a.append(b)
print(a)

enter image description here

I am trying to append one list in another but when I clear one list, it's automatically clearing another list element.

CodePudding user response:

If I understand your question correctly, what you need is to pass the list to other list without REFERENCE. Meaning, you want to modify lists that had been assigned to other lists without affecting these parent lists. In this case, I suggest you use .copy() function on the list. Because, If I am correct, lists are passed by reference:

a = []

b = ['abc']
a.append(b.copy())
print("a after first append:",a)

b.clear()
print("b after clear:",b)
b = ['xyz']
a.append(b)
print("a after second append:",a)

Output

a after first append: [['abc']]
b after clear: []
a after second append: [['abc'], ['xyz']]

Note that, you do not need to use clear since you are reassigning new value to the variable b. But, to make it more clear, I did not change that.

CodePudding user response:

until the first clear, a[0] and b point to the same list, hence clearing either of them will clear the other. if you want it to not be cleared, try appending a copy of the original object, b.copy()

  • Related