The append() method of deque class in Python

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 an already full fixed length deque an element is removed from the left side.

Example 1:

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:

All Grades:

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

All Grades - Updated:

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

 

Example 2:

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:

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)


Copyright 2024 © pythontic.com