list.clear()
Python · Lists
Theory
.clear() removes every item from a list, leaving it empty, and returns None. sales = [100, 250, 300] then sales.clear() leaves sales as []. The important detail is that it empties the same list object rather than creating a new one, so every variable that refers to that list sees it become empty. The items themselves are only freed from memory if nothing else refers to them.
Compare it with sales = []. Assignment creates a brand-new empty list and points only the name sales at it; any other name still refers to the old list with all its items. Which one you want depends on whether other code shares the list. clear() is equivalent to del sales[:]. Dictionaries and sets have a .clear() method that works the same way.
Why we use it
When a list is reused as a buffer or shared between parts of a program, you sometimes need to empty it for everyone at once, for example after writing a batch of rows to a file. clear() does that without breaking the shared reference.
When to use it
Use clear() when other names or objects hold the same list and should all see it empty. Use reassignment (sales = []) when you just want a fresh list for this one name and do not care about other references.
How it works
- Call sales.clear()
- Release the references to every item
- Set the list's length to 0
- The list object itself stays the same
- Does another name refer to this list? Yes: That name now sees [] as well. No: Nothing else is affected.
- print(sales) shows []
Syntax
list.clear()Example
sales = [100, 250, 300]
sales.clear()
print(sales)Key points
- Empties the list in place rather than creating a new one
- Equivalent to del list[:]
- Every alias of the list sees it become empty
- list = [] only rebinds one name; other names keep the old items
- Returns None; dicts and sets have a clear() method too