Difference between del, remove and pop on lists

前端 未结 12 2203
北海茫月
北海茫月 2020-11-22 04:20
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>         


        
12条回答
  •  囚心锁ツ
    2020-11-22 04:44

    Any operation/function on different data structures is defined for particular actions. Here in your case i.e. removing an element, delete, Pop and remove. (If you consider sets, Add another operation - discard) Other confusing case is while adding. Insert/Append. For Demonstration, Let us Implement deque. deque is a hybrid linear data structure, where you can add elements / remove elements from both ends.(Rear and front Ends)

    class Deque(object):
    
      def __init__(self):
    
        self.items=[]
    
      def addFront(self,item):
    
        return self.items.insert(0,item)
      def addRear(self,item):
    
        return self.items.append(item)
      def deleteFront(self):
    
        return self.items.pop(0)
      def deleteRear(self):
        return self.items.pop()
      def returnAll(self):
    
        return self.items[:]
    

    In here, see the operations:

    def deleteFront(self):
    
        return self.items.pop(0)
    def deleteRear(self):
        return self.items.pop()
    

    Operations have to return something. So, pop - With and without an index. If I don't want to return the value: del self.items[0]

    Delete by value not Index:

    • remove :

      list_ez=[1,2,3,4,5,6,7,8]
      for i in list_ez:
          if i%2==0:
              list_ez.remove(i)
      print list_ez
      

    Returns [1,3,5,7]

    let us consider the case of sets.

    set_ez=set_ez=set(range(10))
    
    set_ez.remove(11)
    
    # Gives Key Value Error. 
    ##KeyError: 11
    
    set_ez.discard(11)
    
    # Does Not return any errors.
    

提交回复
热议问题