SoFunction
Updated on 2025-03-05

Four ways to clear list in Python

This article introduces four ways to clear lists, as well as the difference between list=[ ] and () in use (pit).

1. Use the clear() method

lists = [1, 2, 1, 1, 5]
()
print(lists)
>>>[]

2. Reinitialize the list

Initialize the list in this range. Initialize the list without a value, that is, the list of size 0

lists = [1, 2, 1, 1, 5]
lists = []
print(lists)
>>>[]

3. Use “ * = 0”

lists = [1, 2, 1, 1, 5]
lists *= 0
print(lists)
>>>[]

4. Use del

del can be used to clear list elements in ranges, and if we do not give ranges, then delete all elements

lists = [1, 2, 1, 1, 5]
del lists[:]
print(lists)
>>>[]

lists2 = [1, 2, 1, 1, 5]
del lists2[:2]
print(lists2)
>>>[1, 1, 5]

However, when using list=[ ] and () I encountered a problem:

Use first: ()

first = []
last = []
lists_more = [1, 2, 3, 4, 5, 6]

for i in lists_more:
    (i)
    (first)
    ()

print(last)
>>>[]

And use list=[ ]:

first = []
last = []
lists_more = [1, 2, 3, 4, 5, 6]

for i in lists_more:
    (i)
    (first)
    first = []

print(last)
>>>[[1], [2], [3], [4], [5], [6]]

Therefore, in actual use, there is a difference between initialization clearing of lists and clearing using clear(). It involves the reference of memory space. Be careful when facing the problem of multiplexing of lists. It is best to use initialization clearing.

This is the end of this article about four ways to clear lists in Python. For more related Python content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!