Prepend many items to the deque in reverse iteration order.
What You Will Learn
extendleft(iterable) adds elements one by one to the left, reversing their order relative to the input. Use extend() for normal append ordering.
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
values = deque([3, 4])
values.extendleft([1, 2])
print(list(values))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: collections.
- The variable values holds the result of deque([3, 4]). 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(values) prints [2, 1, 3, 4]. Compare that result with the rule above before you change the argument.
Expected output from the example:
[2, 1, 3, 4]
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
Prepend several alert messages and check the final ordering.
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 extendleft([1, 2]) to put 1 before 2 in the resulting deque.
- Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.
Key Takeaways
- Prepend many items to the deque in reverse iteration order.
- extendleft(iterable) adds elements one by one to the left, reversing their order relative to the input.
- Apply this operation only after checking the assumptions and input conditions shown in the example.