I have following very simple implementation in python
m = []
l = []
l.append('A')
l.append('B')
l.append('C')
m.append(l)
l.clear()
print(m) --> this gives empty list.
i tried
m = []
l = []
n = []
l.append('A')
l.append('B')
l.append('C')
n = l
m.append(n)
l.clear()
print(m) --> this gives empty list too
But when i do not clear l, print(m) give me desired list which is ['A','B','C']. Why python clears list m when i clear list l. they are 2 separate variables?
CodePudding user response:
When you are passing a list to another list then it is taking its reference there So when you cleared that list your original list's element is also cleared Try this
m = []
l = []
l.append('A')
l.append('B')
l.append('C')
m.append(l.copy()) -> use list.copy()
l.clear()
print(m)
CodePudding user response:
both variables are reference pointing to the same object. to make a new list you need to do : n = l[:]