0

I have two list that I combine into a single list. Later I want to make a copy of this list so I can do some manipulation of this second list without affecting my first list. My understanding is if you use this [:] it should unlink the list and make a second copy of the list in a independent memory location. My problem is Im not see that work for this scenario I have. I have also tried using list command as well, but the result was the same.

a = ['a','b','c']
b = ['1','2','3']
c = [a[:],b[:]] # list of list

d = c[:] # want to create copy of the list of list so I can remove last item
for item in d:
    del item[-1]

# this is what I am getting returned.
In [286]: c
Out[286]: 
[['a', 'b'], ['1', '2']]

In [287]: d
Out[287]: 
[['a', 'b'], ['1', '2']]
bytes1234
  • 155
  • 4
  • 12

2 Answers2

2

[:] only makes a shallow copy. That is, it copies the list itself but not the items in the list. You should use copy.deepcopy.

import copy
d = copy.deepcopy(c)

Think of a list as having pointers to objects. Now your variable is a pointer to the list. What [:] does is create an entirely new list with the same exact pointers. copy.deepcopy copies all attributes/references within your object, and the attributes/references within those attributes/references.

noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67
0

You have come across the concept of shallow and deep copy in Python.

The slice operator works well when the list structures do not have any sublists.

list1 = ['a', 'b', 'c', 'd']
list2 = list1[:]
list2[1] = 'x'
print list1
['a', 'b', 'c', 'd']
print list2
['a', 'x', 'c', 'd']

This seems to work fine, but as soon as a list contains sublists, we have the same difficulty, i.e. just pointers to the sublists.

list1 = ['a', 'b', ['ab', 'ba']]
list2 = list1[:]

If you assign a new value to an element of one of the two lists, there will no side effect, however, if you change one of the elements of the sublist, the same problem will occur.

This is similar to you modifying the contents of the sublist a and b in c.

To avoid this problem you have to use deepcopy to create a deepcopy of the lists.

This can be done as follow:

from copy import deepcopy

list1 = ['a', 'b', ['ab', 'ba']]
list2 = deepcopy(list1)
Aditya
  • 1,172
  • 11
  • 32