I am trying to have a queue using deque in python.
The error I keep getting is index out of range
perf_his[b][c] = 0
IndexError: deque index out of range
Here is a small prototype of the code that I implemented.
import collections
apps = [1,2,3]
num_thrs = len(apps)
perf_his = []
for a in range(num_thrs):
perf_his += [collections.deque(maxlen=1)]
for b in range(num_thrs):
for c in range(0, 1):
perf_his[b][c] = 0
Inorder to check if I did understand deque correctly, I implemented this code:
#!/usr/bin/env python
from collections import deque
something = ["foo","bar","baz"]
output = []
diff = 0
d = deque()
for i in something:
d.append(i)
print("-> %s" % i)
for i in xrange(len(d)):
print(d[i])
output.append(d[i])
for i in xrange(len(something)):
if output[i] != something[i]:
diff += 1
print(something,output,diff)
I've been trying to fix the error in like 2 days, I don't seem to understand the problem. can someone please shed some light?
In your first bit of code, you never append()
to the deque
, and thus it never has an element "0", and thus you aren't allowed to assign to it. Setting maxlen
doesn't create elements, it just limits how many elements can be present later on.
What you probably want instead is this:
for a in range(num_thrs):
perf_his += [collections.deque()]
for b in range(num_thrs):
for c in range(0, 1):
perf_his[b].append(0)