0

The objective here is to get a list `[1,2,3,4], and add it as is, to another list; so I can have a list of lists

masterlist = [[1,2,3,4],[5,6,7,8],.....]

But I can't get this right.

I did try append, which works, but it copy a reference to that list that I append, it does not copy the values, so if I empty the list that I did append, I end up with the whole thing being cleared.

list1 = [1,2,3,4]

masterlist.append(list1)

del list1[:]
list1 = [5,6,7,8]

masterlist.append(list1)

This result in the masterlist having 2 lists, but they are fundamentally the same, so it will look like this:

[[5,6,7,8],[5,6,7,8]]

While I want [[1,2,3,4],[5,6,7,8]]

I did try to use extend, but this add every element of the current list, as single entry in the other list, so I end up with

[1,2,3,4,5,6,7,8]

How do you end up adding in a list, the content itself of the list, and not the reference?

EDIT: This is not a question related to deep or shallow copy; the other linked question seems similar but did not solve my problem. I see a solution here that fits perfectly my case

  • 2
    If you want to append a copy, [make a copy](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list). Python won't implicitly make copies everywhere like C++. – user2357112 May 09 '17 at 23:16
  • Why did you use `del`? Anyway, you may be interested in importing `copy` and using that to make a copy of `list1` to append. – Arya McCarthy May 09 '17 at 23:17
  • Also, the code you posted doesn't produce the output you describe, because `list1 = [5,6,7,8]` makes a new list object. You'll need to get used to what operations make a new object and what operations modify an existing one. – user2357112 May 09 '17 at 23:18
  • I just learned that Python does not work like C++; the assumption was that adding a list to another list, implicitly create a list in that list object and put every element in it. Thanks for the clarification –  May 09 '17 at 23:43
  • Not sure why you mark this as duplicate: the other questions are nothing like this. And as proof that anyone else looking for an answer to a question like mine, will most likely find this reply. In the same way that I did not see the other 2 questions related to my case. They may be related from the academic point of view, but they won't clarify why what I was doing was happening, nor how to solve it. As matter of respect toward dawg, you should not even consider to close this. –  May 10 '17 at 06:08

1 Answers1

2

You can do:

>>> masterlist = [[1,2,3,4],[5,6,7,8]]
>>> list1 = [1,2,3,4]
>>> masterlist[len(masterlist):]=[list1[:]]
>>> del list1
>>> masterlist
[[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]

Or,

masterlist.append(list1[:])

Or, Python3 only:

masterlist.append(list1.copy())
dawg
  • 98,345
  • 23
  • 131
  • 206