Method Name:
appendleft
Method Signature:
appendleft()
Method Overview:
- appendleft() adds an element to the left side of the deque object.
- On a deque object with fixed length when an element is added at the left side, an element is removed at the right side.
Example 1:
import collections
writerDeque = collections.deque()
print("Contents of writerDeque as writers are added to left:")
writerDeque.appendleft("Pen") print(writerDeque) writerDeque.appendleft("Pencil") print(writerDeque) writerDeque.appendleft("Marker") print(writerDeque) |
Output:
Contents of writerDeque as writers are added to left: deque(['Pen']) deque(['Pencil', 'Pen']) deque(['Marker', 'Pencil', 'Pen']) |
Example 2:
import collections
numberDeque = collections.deque(maxlen=3)
print("Contents of numberDeque as numbers are added to left:")
numberDeque.appendleft(1) print(numberDeque) numberDeque.appendleft(2) print(numberDeque) numberDeque.appendleft(3) print(numberDeque) print("Deque size:%d"%(len(numberDeque)))
# When the deque has reached maximum length print("Adding after deque has reached maximum length") numberDeque.appendleft(3) print(numberDeque) print("Deque size:%d"%(len(numberDeque))) |
Output:
Contents of numberDeque as numbers are added to left: deque([1], maxlen=3) deque([2, 1], maxlen=3) deque([3, 2, 1], maxlen=3) Deque size:3 Adding after deque has reached maximum length deque([3, 3, 2], maxlen=3) Deque size:3 |