Python .clear()
The .clear() method in Python’s collections.deque class removes all elements from the deque, leaving it empty. It’s useful when the contents of the deque need to be cleared without deleting the object itself.
The method modifies the deque in place and returns None. Its time complexity is O(n) since it removes elements one by one.
Syntax
deque.clear()
Parameters:
None: This method does not take any parameters as it simply resets the deque to empty.
Return value:
The return value of .clear() should be a check to determine if the deque is empty. This can be done using an if statement with a return value of true when checked if empty or simply a print() statement to output the length of the deque.
Example 1: Clearing All Elements from a Deque
In this example, the .clear() method removes every element from the deque, and an if statement checks whether it is empty afterward:
from collections import deque# Create a dequecars = deque(["toyota", "suzuki", "honda"])print(f"Initial deque is as follows: {cars}")# Clearing the dequecars.clear()# If statement to check if the deque has been sucessfully clearedif not cars:print("the deque is empty")
The output of this code is:
Initial deque: deque(['Toyota', 'Suzuki', 'Honda'])The deque is empty.
Codebyte Example: Clearing Completed Tasks
In this example, a deque keeps track of recent tasks in a to-do list. After all tasks are completed, the .clear() method is used to empty the deque and prepare it for new tasks:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours