Search code examples
python-3.xdeque

Python: modify a deque inside a function


I know that it is possible to modify a list inside a function by using assignment as followslis[:] = new_list, however the question is, is it possible to modify a deque inside a function as it is also an iterable? Of course without using return inside the function.

It not possible to use 'deq[:] = new_deq ' as it gives the following error: TypeError: sequence index must be integer, not 'slice'


Solution

  • deque does not support a slice as an index, so to achieve the effect of lis[:] = new_list with a deque, you can clear it first before extending it:

    from collections import deque
    
    def f(q, new_list):
        q.clear()
        q.extend(new_list)
    
    d = deque([1, 2])
    f(d, [2, 3])
    print(d)
    

    This outputs:

    deque([2, 3])