Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically appending one list into another

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading