2

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.

  • 1
    Does this answer your question? [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Joe Jun 06 '20 at 02:25
  • the problem is ur clearing it with `temp.clear()` everytime the loop re-runs, i guess. Try removing it – Delrius Euphoria Jun 06 '20 at 02:41

1 Answers1

2

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!

Sam
  • 1,406
  • 1
  • 8
  • 11
  • You could skip the `copy` module and just use the canonical shallow copy slice: `list1.append(temp[:])` or (since 3.3) `list1.append(temp.copy())`. You only really need the `copy` module if the `list` contains mutable objects, in which case you reach for `copy.deepcopy`. – ShadowRanger Jun 06 '20 at 02:39
  • Did you read my 2nd answer below the code? It does not use `copy` either. Lots of ways, thanks Python! – Sam Jun 06 '20 at 02:59
  • Yeah, I did. Just pointing out that neither of them need it. Personally, I favor your second solution (rebinding a fresh new `list`), as it's simpler and likely faster. – ShadowRanger Jun 06 '20 at 03:11