Dynamically appending one list into another

Question:

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?

Asked By: jaykio77

||

Answers:

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) 
Answered By: Deepak Tripathi

Both variables are reference pointing to the same object. to make a new list you need to use n = l[:]

Answered By: youen

An alternative to list.copy:

m.append(l[:])

or

m.append(list(l))

The will append to m a "freshly" created list.

In some situations also a deep copy of the object could be the right solution:

from copy import deepcopy
...
m.append(deepcopy(l))
...
Answered By: cards
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.