Skip to content
Advertisement

Initialize deque efficiently

I am using a deque to store data that is going to be processed. The processing only starts when the deque is full so in a first step I fill my buffer the following way:

from collections import deque
import numpy as np

my_deque = deque(maxlen=10)
dims = (20, 20)
my_deque.extend([np.ones(dims)] * 10)

However, when I do this and I modify one of the elements of my_deque, all elements of my_deque are modified.

One alternative I found to avoid this issue is to initialize my deque the following way

for i in range(10):
    my_deque.append(np.ones(dims))

Is there a more elegant way to achieve this?

Edit: One example of modification that create the issue is the following

my_deque[7][2, :] = 0

After this line of code, the third row of every element of my_deque is a row of zeros, not just the one at index 7

Advertisement

Answer

@MichaelSzczesny’s comment was the right answer, it seems to have been deleted so I post it here:

from collections import deque
import numpy as np

my_deque = deque(maxlen=10)dims = (10, 20, 20)
my_deque.extend(np.ones(dims))
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement