There is a clear() method in Python that clears the list.

Suppose I have an array of a = [1,2,3] I now need to make an array empty. In my experience I know 2 approaches to solving this problem.

  1. a.clear()
  2. a = []

Or OOP's version:

 class A: def __init__(self): self.a = [1,2,3] def clear1(self): self.a.clear() def clear2(self): self.a = [] 

The question is: what is the difference between these two approaches, and if there is a difference, what and when will it be more optimal to use?

  • 1) Items from the list will be deleted 2) An empty list will be created, and the previous one will remain alive until the garbage collector gets to it - gil9red

2 answers 2

The difference will be if you assign this array to other variables. In the case of clear() after cleaning both will be assigned the same object as before cleaning:

 a = [1,2,3] print(id(a)) # 43108936 b = a print(id(b)) # 43108936 print(a) # [1, 2, 3] print(b) # [1, 2, 3] a.clear() print(id(a)) # 43108936 print(id(b)) # 43108936 print(a) # [] print(b) # [] print(a is b) # True print(b is a) # True 

In the case of assigning an empty array, the variable b will continue to store a reference to the original object:

 a = [1,2,3] print(id(a)) # 43108424 b = a print(id(b)) # 43108424 print(a) # [1, 2, 3] print(b) # [1, 2, 3] a = [] print(id(a)) # 43108680 print(id(b)) # 43108424 print(a) # [] print(b) # [1, 2, 3] print(a is b) # False print(b is a) # False 

    There are 2 more ways:

    1 :

     x = [1, 2, 3, 4] del x[:] 

    When assigning an empty list, the identifier changes:

     x = [1, 2, 3, 4] id(x) >>> 48068488 x.clear() id(x) >>> 48068488 x = [] id(x) >>> 48071904 # изменяется идентификатор