Search code examples
pythondeque

Why does deque.extendleft() reverse the order of elements?


From official documentation:

extendleft(iterable)

   Extend the left side of the deque by appending elements from iterable. Note, the 
   series of left appends results in reversing the order of elements in the iterable argument.

What is the reason/concept behind this method's behaviour? I know I can easily change it by using reversed, but I'm just curious.


Solution

  • Lets say you are extending with [1, 2, 3, 4]. The iterable will be iterated and each element will be appended to the left. So, the process goes like this

    Read the first element and put it at the left end

    1
    

    Read the second element and put it at the left end

    2 -> 1
    

    Read the third element and put it at the left end

    3 -> 2 -> 1
    

    Read the fourth element and put it at the left end

    4 -> 3 -> 2 -> 1
    

    See, the order of the elements is reversed. Actually, this seems logical to me. When we do list.extend, like this

    [].extend([1, 2, 3, 4])
    

    The iterable is iterated and added to the right end of the list. So, the pattern is followed with extendleft as well.