0
list = [1,2,3,4,5]
list.clear()
print(list)

O/P : [ ]

list = [1,2,3,4,5]
list=[]
print(list)
O/P : [ ]

Both the case I am getting same output. So what's the difference between these two?

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Rajat Bain
  • 11
  • 1

1 Answers1

4

clear() will keep the same reference, but empty the list. [] creates a new list and assigns it to the variable.

Example:

>>> a = [1,2,3]
>>> b = a
>>> a is b
True
>>> a.clear()
>>> a is b
True
>>> a = []
>>> a is b
False

Note that a and b are still the same object after the clear, but different objects after you assign a new list to a.

Loocid
  • 6,112
  • 1
  • 24
  • 42