Error in collections-deque - Python
Question: 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?


Answer: 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)
    

