Populating deque

As we have already read that deque is a double-ended queue, hence it means elements can be added from either side or the deque can be populated from either side. In order to add elements or populate the deque, we have four functions: extend(), append(), extendleft(), and appendleft(). Let's take an example to illustrate how we can populate or add elements to both sides of the deque:

import collections
d1 = collections.deque("Google")
print d1
d1.extend('raj')
print "after extend :n", d1
d1.append('hi')
print "After append :n",d1

d1.extendleft("de")
print "after extend leftn ", d1

d1.appendleft("le")
print "after append leftn ", d1

Here, in this case, we are providing "Google" as input to the deque. We then extend the list by passing 'raj' as the input and it is extended to the right-hand side of the deque. We append another input to the right-hand side of the deque. In order to add elements to the left, we use extendleft() and appendleft(). The output of the program will clear the doubts as shown:

The functions extend() and append() both add elements to any collection. The only difference is that extend() adds each element to the collection one by one, while append() considers all the elements as one and appends all at the end of the collection. For example, extend(['Dunkirk','Calais']) adds two elements 'Dunkirk' and 'Calais' one by one to the collection. While append(['Dunkirk','Calais']) considers both of them as one element and adds to the end of the collection.

The extendleft() function iterates over its input and performs the equivalent of an appendleft() for each item. The final outcome is that the deque contains the input sequence in reverse order.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.77.153