0

I have a list consisting of just one dictionary item. I want to modify this item and append it to another list. When I append to another list, it still retains the pointers since it copies by reference by design.

As per this link even if the list is copied using [:] notation, it still retains the link to its inner objects.

My question is how do I get around this limitation or is there a workaround for what I am trying to achieve? Here is the code snippet:

a=[]
b=[]
a=[{'sk' : 1, 'id' : 'P001', 'status' : 'NEW'}]
a[0]['sk']=a[0]['sk']+1
a[0]['status']='CURRENT'
b.append(a[0])
a[0]['sk']=a[0]['sk']+1
a[0]['status']='EXISTING'
b.append(a[0])
b
[{'id': 'P001', 'sk': 3, 'status': 'EXISTING'},
{'id': 'P001', 'sk': 3, 'status': 'EXISTING'}]

As you can see, changing [a] changes all elements in [b]. I also tried changing b[0], b1 etc. It still does the same.

Are there any workarounds for what I am trying to do?

Community
  • 1
  • 1
Arvind Kandaswamy
  • 1,821
  • 3
  • 21
  • 30

3 Answers3

2

You can use .copy() to copy the inner dict

>>> a = []
>>> b = []
>>> a=[{'sk' : 1, 'id' : 'P001', 'status' : 'NEW'}]
>>> a[0]['sk'] += 1
>>> a[0]['status']='CURRENT'
>>> b.append(a[0].copy())
>>> a[0]['sk'] += 1
>>> a[0]['status']='EXISTING'
>>> b.append(a[0].copy())
>>> b
[{'sk': 2, 'status': 'CURRENT', 'id': 'P001'},
 {'sk': 3, 'status': 'EXISTING', 'id': 'P001'}]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

To copy lists, arrays and objects without only copying the pointer use this library: https://docs.python.org/2/library/copy.html

And than a = copy.deepcopy(b)

Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
1

You just need to call .copy() on a when you append it to b.

b = []
a = [{'sk' : 1, 'id' : 'P001', 'status' : 'NEW'}]
a[0]['sk'] += 1
a[0]['status'] = 'CURRENT'
b.append(a[0].copy())
a[0]['sk'] = a[0]['sk']+1
a[0]['status'] = 'EXISTING'
b.append(a[0])
print(b)

[{'sk': 2, 'id': 'P001', 'status': 'CURRENT'}, {'sk': 3, 'id': 'P001', 'status': 'EXISTING'}]
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67