List method

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.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

Pythoneditable
basket = ["apple", "bread", "cheese"]
basket.clear()
print(basket)
print(len(basket))
Output
[]
0

2clear() vs assigning a new list

Pythoneditable
a = [1, 2, 3]
shared = a
a.clear()
print(shared)
b = [1, 2, 3]
other = b
b = []
print(other)
Output
[]
[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

Pythoneditable
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)
Output
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.

Pythoneditable
rounds = []
scores = [10, 20]
rounds.append(scores)
scores.clear()
print(rounds)
rounds = []
scores = [10, 20]
rounds.append(scores.copy())
scores.clear()
print(rounds)
Output
[[]]
[[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.

Spotted a mistake on this page? Tell us