|
| 1 | +--- |
| 2 | +Title: '.clear()' |
| 3 | +Description: 'Removes all elements from the deque, leaving it empty.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Algorithms' |
| 9 | + - 'Collections' |
| 10 | + - 'Data Structures' |
| 11 | + - 'Deques' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/computer-science' |
| 15 | +--- |
| 16 | + |
| 17 | +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. |
| 18 | + |
| 19 | +The method modifies the deque in place and returns `None`. Its time complexity is `O(n)` since it removes elements one by one. |
| 20 | + |
| 21 | +## Syntax |
| 22 | + |
| 23 | +```pseudo |
| 24 | +deque.clear() |
| 25 | +``` |
| 26 | + |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `None`: This method does not take any parameters as it simply resets the deque to empty. |
| 30 | + |
| 31 | +**Return value:** |
| 32 | + |
| 33 | +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. |
| 34 | + |
| 35 | +## Example 1: Clearing All Elements from a Deque |
| 36 | + |
| 37 | +In this example, the `.clear()` method removes every element from the deque, and an `if` statement checks whether it is empty afterward: |
| 38 | + |
| 39 | +```py |
| 40 | +from collections import deque |
| 41 | + |
| 42 | +# Create a deque |
| 43 | +cars = deque(["toyota", "suzuki", "honda"]) |
| 44 | +print(f"Initial deque is as follows: {cars}") |
| 45 | + |
| 46 | +# Clearing the deque |
| 47 | +cars.clear() |
| 48 | + |
| 49 | +# If statement to check if the deque has been sucessfully cleared |
| 50 | +if not cars: |
| 51 | + print("the deque is empty") |
| 52 | +``` |
| 53 | + |
| 54 | +The output of this code is: |
| 55 | + |
| 56 | +```shell |
| 57 | +Initial deque: deque(['Toyota', 'Suzuki', 'Honda']) |
| 58 | +The deque is empty. |
| 59 | +``` |
| 60 | + |
| 61 | +## Codebyte Example: Clearing Completed Tasks |
| 62 | + |
| 63 | +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: |
| 64 | + |
| 65 | +```codebyte/python |
| 66 | +from collections import deque |
| 67 | +
|
| 68 | +# Create a deque of completed tasks |
| 69 | +completed_tasks = deque(["Write report", "Send emails", "Backup files"]) |
| 70 | +print(f"Completed tasks: {completed_tasks}") |
| 71 | +
|
| 72 | +# Clear all tasks to reuse the deque for a new session |
| 73 | +completed_tasks.clear() |
| 74 | +
|
| 75 | +print(f"Tasks after clearing: {completed_tasks}") |
| 76 | +``` |
0 commit comments