list.clear()
Empties a list in place, so the same list object ends up with no items. Every variable pointing to it sees the change.
list.clear()clear() deletes all items from a list. The list still exists, it is just empty, exactly like [].
Use it to reuse a list, for example a buffer that you fill, process and empty again in a loop.
The difference from items = [] matters when two names point to the same list. clear() empties that one shared list, so both names see an empty list. items = [] only makes one name point to a new, empty list and leaves the old one untouched.
Return value
Nothing (None). The list is changed in place.
Examples
1Empty a list
basket = ["apple", "bread", "cheese"]
basket.clear()
print(basket)
print(len(basket))[] 0
2clear() vs assigning a new list
a = [1, 2, 3]
shared = a
a.clear()
print(shared)
b = [1, 2, 3]
other = b
b = []
print(other)[] [1, 2, 3]
clear() empties the one list both names share. b = [] only moves the name b; other still sees the old list.
3Process items in batches
batch = []
for order in [101, 102, 103, 104, 105]:
batch.append(order)
if len(batch) == 2:
print("Sending", batch)
batch.clear()
print("Left over:", batch)Sending [101, 102] Sending [103, 104] Left over: [105]
Common mistakes
Clearing a list you already stored elsewhere
Storing a list in another list keeps a reference, not a copy. Clearing it afterwards empties the stored one too. Store a copy, or start a new list instead of clearing.
rounds = []
scores = [10, 20]
rounds.append(scores)
scores.clear()
print(rounds)
rounds = []
scores = [10, 20]
rounds.append(scores.copy())
scores.clear()
print(rounds)[[]] [[10, 20]]
Questions people ask
What is the difference between clear() and del items[:]?
None in practice: both empty the list in place. clear() is easier to read.
How do I delete the list itself?
del items removes the name. The list is freed once nothing else points to it.
Do dictionaries and sets have clear() too?
Yes: dict.clear() and set.clear() work the same way.