Content · Programming · Python

Python deque.appendleft() Method: Usage and Examples

Insert an item at the front of a deque.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Insert an item at the front of a deque.

What You Will Learn


appendleft(value) inserts at the left end in constant-time amortized behavior. A bounded deque can discard an item from the opposite end when full.

Time complexity assumes a specific input structure. Include setup work such as sorting or building a lookup table when comparing complete solutions.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from collections import deque
requests = deque(['normal', 'later'])
requests.appendleft('urgent')
print(list(requests))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: collections.
  • The variable requests holds the result of deque(['normal', 'later']). Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression list(requests) prints ['urgent', 'normal', 'later']. Compare that result with the rule above before you change the argument.

Expected output from the example:

['urgent', 'normal', 'later']

When You Would Use This


This technique matters when a program handles larger queues, sorted records, or repeated lookups. Choose the data structure based on actual operations and the preconditions the algorithm requires. Verify boundary inputs before optimizing for speed.

Practice: Modify the Code


Add a high-priority message ahead of existing pending messages.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Expecting appendleft() to return the modified deque; it returns None.
  • Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.

Key Takeaways


  • Insert an item at the front of a deque.
  • appendleft(value) inserts at the left end in constant-time amortized behavior.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.