The append() method of deque class in Python

The append() adds an element to the right side of the deque object. As an element is appended to the right side of a deque which is already full and is of fixed-lengt an element is removed from the left.

Deque Updated 19 Mar 2017 1 min read

Method signature

append(object)

Return value

None

Overview

  • The append() method adds an element to the right side of a deque.
  • When an element is appended at the right side of a fixed length deque which is already full an element is removed from the left side to accomodate the new element.

Appending an element when the deque is full

Example 1

python
import collections

gradeTuple = ("good", "better", "best")

# Create a deque from a tuple of strings

gradeDeque = collections.deque(gradeTuple)

print("All Grades:")

print(gradeDeque)

# Add a new grade

print("All Grades - Updated:")

gradeDeque.append("awesome")

print(gradeDeque)

Output

Output
All Grades:

deque(['good', 'better', 'best'])

All Grades - Updated:

deque(['good', 'better', 'best', 'awesome'])

Example 2

python
import collections

# Create an empty deque

d1 = collections.deque(maxlen=3)

print(d1)

d1.append("Small")

d1.append("Medium")

d1.append("Large")

# After filling the deque to maximum length

print("Deque at maximum length...")

print("Deque Length:%d"%(len(d1)))

print(d1)

d1.append("Extra Large")

print("Deque after adding a 4th elem to the right side:")

print("Deque Length:%d"%(len(d1)))

print(d1)

Output

Output
deque([], maxlen=3)

Deque at maximum length...

Deque Length:3

deque(['Small', 'Medium', 'Large'], maxlen=3)

Deque after adding a 4th elem to the right side:

Deque Length:3

deque(['Medium', 'Large', 'Extra Large'], maxlen=3)