Python list clear: Remove all the elements from a list

All the elements of a Python list are removed by clear method.

a = [1, 2, 3]

a.clear()

print(a)  # []

After cleared, a list is updated to an empty list.

List id before and after clearing

In Python, id returns the identity of object.

a = [1, 2, 3]

print(id(a))  # 4584708544
print(id([1, 2, 3]))  # 4584709376

a.clear()

print(id(a))  # 4584708544
print(id([1, 2, 3]))  # 4584709376

Id of a doesn't change before and after clearing. The fact that ids of a and [1, 2, 3] are different is important for understanding Python assignment.

Why does Python have clear method? a can be updated to an empty list as follows.

a = [1, 2, 3]
a = []

This is simpler but some Python programmers prefer clear method because of object id.

a = [1, 2, 3]

print(a)  # [1, 2, 3]
print(id(a))  # 4673763712

a = []

print(a)  # []
print(id(a))  # 4673764544

a = [] changes id of a.

Python List

Python Tutorial