A checkout application resets its basket after completing an order.
What You Need to Understand
list.clear() removes all items from the existing list and returns None. References to that same list all see the cleared state.
When to Use It
A checkout application resets its basket after completing an order.
Step-by-Step Python Example
basket = ["pen", "paper"]
original_reference = basket
basket.clear()
print(basket)
print(original_reference)
How the Example Works
Both names now refer to the same empty list, because clear() modified the object.
Example Output
[]
[]
None
[]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
items = [1, 2]
print(items.clear())
print(items)
Important Behavior and Edge Cases
Reassigning basket = [] creates a new list and does not clear old references; that is not equivalent when the list is shared.
Try It Yourself
Compare clear() with reassigning to a new empty list.
Common Beginner Mistakes
- Reassigning
basket = []creates a new list and does not clear old references; that is not equivalent when the list is shared. - Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
list.clear()removes all items from the existing list and returnsNone.- Both names now refer to the same empty list, because
clear()modified the object. - Reassigning
basket = []creates a new list and does not clear old references; that is not equivalent when the list is shared.