Home > Enterprise >  Different between List.clear and List = [] in Python
Different between List.clear and List = [] in Python

Time:10-31

What is the difference array.clear() and array = [] in the following two implementations.

1)print output is [1,2,3,4,5]

class fistclass_():
   def __init__(self):
        self.array = None
   def setarray(self):
        array = [1,2,3,4,5]
        self.array = array
        array = []
        return     

class anotherclass_():
   def copylist(self,array):
        self.a = array
        print(self.a)

def main():
    f = fistclass_()
    f.setarray()
    a = anotherclass_()
    a.copylist(f.array)
main()
  1. print empty array
class fistclass_():
       def __init__(self):
            self.array = None
       def setarray(self):
            array = [1,2,3,4,5]
            self.array = array
            array.clear()
            return     
    
    class anotherclass_():
       def copylist(self,array):
            self.a = array
            print(self.a)
    
    def main():
        f = fistclass_()
        f.setarray()
        a = anotherclass_()
        a.copylist(f.array)
    main()

CodePudding user response:

If you have more than one reference to a list, then .clear() clears the list and preserves the references, but the assignment creates a new list and does not affect the original list.

a = [1,2,3]
b = a # make an additional reference
b.clear()
print(a, b)
# [] []
a = [1,2,3]
b = a # make an additional reference
b = []
print(a, b)
#[1, 2, 3] []

Interestingly, you can clear the contents through an assignment to a full list slice:

a = [1,2,3]
b = a # make an additional reference
b[:] = []
print(a, b)
#[] []

CodePudding user response:

When you do array.clear(), that tells that existing object to clear itself. When you do array = [], that creates a brand-new object and replaces the one it had before. The new array object is unrelated to the one you stored in self.array.

  • Related