-3

I created a copy of a list. When an item was removed from one copy - it was removed from the original as well.

a = ['alpha', 'beta', 'gamma', 'delta']
b = a

b.remove('alpha')

print 'A list is', a
print 'B list is', b

How should I create an independent copy of the list, that will not impact the original?

Late addition

To understand the reason for this mistake - one should refer to the difference between Shallow Copy and Deep Copy Python documentation - 8.17. copy

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Community
  • 1
  • 1
DarkLight
  • 79
  • 3
  • 16
  • I just got a -1 w/o any comment - That's not helpful. If you think that question is irrelevant, wrong or useless - please explain (or tag accordingly) – DarkLight Nov 15 '18 at 08:50

1 Answers1

1

You can use in-built copy module.

import copy
a = ['alpha', 'beta', 'gamma', 'delta']
# it will perform the shallow copy
b = copy.copy(a)

b.remove('alpha')

print 'A list is', a
print 'B list is', b

For Python3.x. Though, copy module is available in Python3.x

a = ['alpha', 'beta', 'gamma', 'delta']
b = a.copy()

b.remove('alpha')

print('A list is', a)
print('B list is', b)

Hope this helps

Srce Cde
  • 1,764
  • 10
  • 15