-2

I just realized now that when I append a list to another list and I delete this appended list, the list also wont be in the other list. Makes maybe sense, because appending a list to somewhere else is just a reference. So when I'm using something like this:

B[:] = []

Then it will be gone from everywhere. How can I avoid this issue? Using copy? My problem is that I'm collecting lists in a list and at some point I'm adding this whole thing to another list - after that I would like to make the added list empty to use it to adding new data to it.

silla
  • 1,257
  • 4
  • 15
  • 32
  • what you mean by : *when I'm using something like this:`B[:] = []` Then it will be gone from everywhere* ? – Mazdak Nov 07 '14 at 12:37
  • @Kasra: the list is empty, and its also not in the other list where it was appended – silla Nov 07 '14 at 12:38
  • possible duplicate of [Python references](http://stackoverflow.com/questions/2797114/python-references) – simonzack Nov 07 '14 at 12:40
  • possible duplicate of [How to clone or copy a list in Python?](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python) – bakkal Nov 07 '14 at 12:43

3 Answers3

1
>>> a = [1, 2, 3, 4]
>>> b = list()
>>> b.append(a[:])
>>> a = []
>>> b
[[1, 2, 3, 4]]
Darth Kotik
  • 2,261
  • 1
  • 20
  • 29
1

You need to copy the List in another object and should operate then:-

a, b = range(10), []
c = a[:]
b.append(c)
a[:] = []
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
1

I think easiet way will be:

>>> a = []
>>> b = ['k']
>>> a.append(list(b))
>>> b[:] = []
>>> b
11: []
>>> a
12: [['k']]
Kokoman
  • 86
  • 2