Python Tutorial

Python List clear() Method with Examples (clear vs [] vs del)

TGTeam GyaniPanditNovember 30, 20262 min read

The clear() method removes all items from a list, leaving it empty. The list itself still exists, so you can keep adding to it. This page explains clear() with outputs, shows the other ways to empty a list, and explains the one difference that really matters: clear() vs assigning [].

Syntax

list.clear()

It takes no arguments and returns None.

Basic Example

nums = [10, 20, 30, 40]
nums.clear()
print(nums, len(nums))

Output:

[] 0
Python list clear method example

clear() vs list = []

Both make a list look empty, but they work differently when another variable points to the same list:

a = [1, 2, 3]
b = a          # b refers to the SAME list
a.clear()
print(a, b)

a = [1, 2, 3]
b = a
a = []         # a now refers to a NEW empty list
print(a, b)

Output:

[] []
[] [1, 2, 3]

clear() empties the list object itself, so every variable that refers to it sees the change. a = [] only points a to a brand-new list; the old list, still referenced by b, is untouched. Use clear() when other parts of your program share the list and should all see it emptied.

Other Ways to Empty a List

c = [1, 2, 3]
del c[:]       # delete every item using a slice
print(c)

d = [1, 2, 3]
d *= 0         # repeat the list zero times
print(d)

Output:

[]
[]

Both work in place like clear(), but clear() is the clearest to read.

Emptying a Python list using del

Do Not Confuse clear() with del list

e = [1, 2, 3]
del e
print(e)
NameError: name 'e' is not defined

del e deletes the variable itself, not just its contents. After it, the name e no longer exists.

clear() Returns None

print([5, 6].clear())

Output:

None

So never write my_list = my_list.clear(); that would set my_list to None.

clear() on Other Collections

cart = {'pen': 2}
cart.clear()
print(cart)

s = {1, 2}
s.clear()
print(s)

Output:

{}
set()

Dictionaries and sets also have a clear() method. Tuples and strings do not, because they are immutable.

Frequently Asked Questions

What does list.clear() return?

None. It empties the list in place.

What is the difference between clear() and del?

clear() removes all items but keeps the list; del my_list removes the variable completely.

Is clear() available in Python 2?

No, list.clear() was added in Python 3.3. In older code you may see del my_list[:] instead.

Related: Python list sort() · Accessing tuple elements

Turn reading into skillsCertificate courses in AI, Data Science and programming.
Explore Courses