📜  在Python中清除列表的不同方法

📅  最后修改于: 2022-05-13 01:55:07.116000             🧑  作者: Mango

在Python中清除列表的不同方法

有很多方法可以通过Python语言提供的不同构造的方法来清除列表。让我们尝试一一了解每种方法。

  • 方法 #1:使用clear()方法
    # Python program to clear a list
    # using clear() method 
      
    # Creating list
    GEEK = [6, 0, 4, 1]
    print('GEEK before clear:', GEEK) 
      
    # Clearing list 
    GEEK.clear() 
    print('GEEK after clear:', GEEK) 
    

    输出:

    GEEK before clear: [6, 0, 4, 1]
    GEEK after clear: []
    

  • 方法#2:重新初始化列表:在该范围内初始化列表,初始化没有值的列表。即大小为 0 的列表。让我们看看演示方法 1 和 2 以清除列表的示例
    # Python3 code to demonstrate 
    # clearing a list using
    # clear and Reinitializing 
      
    # Initializing lists
    list1 = [1, 2, 3]
    list2 = [5, 6, 7]
      
    # Printing list1 before deleting 
    print ("List1 before deleting is : " 
    +  str(list1))
      
    # deleting list using clear()
    list1.clear()
      
    # Printing list1 after clearing
    print ("List1 after clearing using clear() : " 
    + str(list1))
      
    # Printing list2 before deleting 
    print ("List2 before deleting is : "
     +  str(list2))
      
    # deleting list using reinitialization
    list2 = []
      
    # Printing list2 after reinitialization
    print ("List2 after clearing using reinitialization : " 
    + str(list2))
    

    输出:

    List1 before deleting is : [1, 2, 3]
    List1 after clearing using clear() : []
    List2 before deleting is : [5, 6, 7]
    List2 after clearing using reinitialization : []
    

  • 方法#3:使用“*= 0” :这是一种鲜为人知的方法,但这种方法会删除列表中的所有元素并使其为空。
    # Python3 code to demonstrate 
    # clearing a list using
    # *= 0 method
      
    # Initializing lists
    list1 = [1, 2, 3]
      
    # Printing list1 before deleting 
    print ("List1 before deleting is : " + str(list1))
      
    # deleting list using *= 0
    list1 *= 0
      
    # Printing list1 after *= 0
    print ("List1 after clearing using *= 0: " + str(list1))
    

    输出:

    List1 before deleting is : [1, 2, 3]
    List1 after clearing using *= 0: []

  • 方法#4 :使用del : del可用于清除范围内的列表元素,如果我们不给出范围,则删除所有元素。
    # Python3 code to demonstrate 
    # clearing a list using
    # del method
      
    # Initializing lists
    list1 = [1, 2, 3]
    list2 = [5, 6, 7]
      
    # Printing list1 before deleting 
    print ("List1 before deleting is : " + str(list1))
      
    # deleting list1 using del
    del list1[:]
    print ("List1 after clearing using del : " + str(list1))
      
      
    # Printing list2 before deleting 
    print ("List2 before deleting is : " + str(list2))
      
    # deleting list using del
    del list2[:]
    print ("List2 after clearing using del : " + str(list2))
    

    输出:

    List1 before deleting is : [1, 2, 3]
    List1 after clearing using del : []
    List2 before deleting is : [5, 6, 7]
    List2 after clearing using del : []