2

How can I modify a list of deques in python without affecting the other members in the list? I tried deques of deques and got the same results.

maxTrackingObjects=10
pnts = [] #list for points
pntDeque = deque(maxlen=32) #each point is a deque

#10 points each has its deque
for x in range(0,maxTrackingObjects):  
    pnts.append(pntDeque)
    # print(pnts[x])

pnts[0].appendleft(5) #append to all members!!

for x in pnts:
    print (x)

Output:

deque([5], maxlen=32)
deque([5], maxlen=32)
deque([5], maxlen=32)
deque([5], maxlen=32)
deque([5], maxlen=32)
deque([5], maxlen=32)
deque([5], maxlen=32)
deque([5], maxlen=32)
deque([5], maxlen=32)
deque([5], maxlen=32)
martineau
  • 119,623
  • 25
  • 170
  • 301
abeer00
  • 53
  • 1
  • 6
  • change `pnts.append(pntDeque)` to `pnts.append(copy.deepcopy(pntDeque))`, (import `copy` module). See https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list for more info – Dan Mar 05 '20 at 16:24
  • 1
    You're appending the same `object`. Instead you should do `pnts.append(deque(maxlen=32))` which will create a new object. – Chrispresso Mar 05 '20 at 16:26
  • Thanks, got it. This way I am not passing a reference but an actual copy of the dequeue – abeer00 Mar 05 '20 at 16:49

0 Answers0