Reputation: 23
I am trying to append a list to a list using an append function. See the below code - the temp will be a temporary list which is created dynamically. I want to append temp to list1.
temp = []
list1 = []
for num in range(0,2):
temp.clear()
temp.append(num)
list1.append(temp)
print(list1)
The output intended in list1 is [[0],[1]]. However i get [[1],[1]]. Can some one explain the reason behind this. Append should append to a list with out changing the list.
Upvotes: 2
Views: 535
Reputation: 1415
Since you have appended the whole temp
list, then list1
contains a reference to that list. So when you modify temp
with temp.clear()
and temp.append(num)
, then list1 is also modified. If you don't want that to happen, you'll need to append a copy:
import copy
temp = []
list1 = []
for num in range(0,2):
temp.clear()
temp.append(num)
list1.append(copy.copy(temp))
print(list1)
> [[0]]
> [[0], [1]]
Another way to get the desired results is to use temp = []
instead of temp.clear()
. That will make temp
point to a new object in memory, leaving the one that is referenced in list1
unchanged. Both work!
Upvotes: 2