Search code examples
pythonwhile-loopdeque

Python: deque out of index, why?


I have a list with IDs in string format (list_id). I created a deque (de_list_id) with numbers from 1 to length of list_id, so that I can reference to each element of list_id. Furthermore I have a function which checks, if a file (with a certein ID) is back up online or not. I want the loop to repeat until everything is online. I wrote:

while de_list_id:
    k = de_list_id.popleft()  #take the first element and check if it is online
    status = check(arg1, arg2, list_id[de_list_id[k]], arg3)

    if status:
        dl_routine(arg1, arg2, list_id[de_list_id[k]], arg3)  # if so, download and remove
    else:
       de_list_id.append(k)  # if not, append it back to list

But that returns:

IndexError: deque index out of range

Does anyone know why and how to fix that? Any help would be much appreciated. Thanks in advance!


Solution

  • I suspect this is where things are going wrong:

    k = de_list_id.popleft()  
    status = check(arg1, arg2, list_id[de_list_id[k]], arg3)
    

    You pop the index k from the queue, then use it to select index on the queue itself with de_list_id[k]?

    Per your description, I think you want to do something like this instead:

    k = de_list_id.popleft()  
    status = check(arg1, arg2, list_id[k], arg3)
    

    Same for the line dl_routine(arg1, arg2, list_id[de_list_id[k]], arg3) -> dl_routine(arg1, arg2, list_id[k], arg3).