Is there a way to keep the length of a list constant while continuously appending to it during iteration?
I tried deque, but it gives me a runtime error and I read it's not possible to leftpop elements.
I tried it with list.pop(0) and list.append() but the indexes get messed up.
The deque methode would be perfect, specifying a maxlength and then just having a 'rolling window' where slice_items get added if needed for a later do-over, and items at the beginning get popped to not run out of memory. Basically it can run forever until the work is done, no new elements get added back, and the list is depleted
for symbol in symbols:
slices = ['year1month1', 'year1month2', 'year1month3', 'year1month4']
for slice_item in slices:
# do something here
if something didnt work:
slices.pop(0)
slices.append(slice)
...
here my approach with the runtime error:
for symbol in symbols:
slices = deque(['year1month1', 'year1month2', 'year1month3', 'year1month4'],maxlen=24)
for slice_item in slices:
# do something here
if something didnt work:
slices.append(slice)
...
Update, thanks to @Buran; for completeness:
from collections import deque
symbols = ('a','b','...','n')
slices = ('year1month1', 'year1month2', 'year1month3')
for symbol in symbols:
slice_queue = deque(range(len(slices)))
while slice_queue:
slice_idx = slice_queue[0]
# do something
done = symbols + slices[slice_idx]
if done:
slice_queue.popleft()
else:
slice_queue.rotate(-1)