3

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?

pistal
  • 2,310
  • 13
  • 41
  • 65

2 Answers2

2

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)
Amber
  • 507,862
  • 82
  • 626
  • 550
  • Thanks. So, this will have a deque something like this right? assuming the range of thrs is 3 `[[0],[0],[0]]` am I correct? – pistal Jan 27 '13 at 17:44
1

When maxlen is set, the deque still is size zero until elements are added. The effect of maxlen=5 is that after five appends, then next append will automatically pop the oldest element so that the size never get bigger. In other words, maxlen is the maximum size, not the minimum.

For your application, the deque needs to be prepopulated with initial values before you can make any assignments:

>>> d = deque([0] * 5, maxlen=5)
>>> d[2] = 100
>>> d
deque([0, 0, 100, 0, 0], maxlen=5)
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • One other thought -- deques aren't usually the right data structure if you're going to make indexed assignments such as ``d[i] = x``. Deques are primarily designed for appends and pops at the endpoints. – Raymond Hettinger Jan 27 '13 at 18:05