带有示例的Python列表clear()方法
清单clear()方法
clear()方法用于清除列表,即用于从列表中删除所有元素。
语法:
list_name.clear()
Parameter(s):
它不接受任何参数。
返回值:
此方法的返回类型为<class'NoneType'>,它不返回任何内容。
范例1:
#申报名单 cities = ["New Delhi", "Mumbai", "Banglore"] #在清除列表之前打印元素 print("Before clear() method...") print("cities = ", cities) #清除清单 cities.clear() #清除列表后打印元素 print("After clear() method...") print("cities = ", cities)
输出结果
Before clear() method... cities = ['New Delhi', 'Mumbai', 'Banglore'] After clear() method... cities = []
范例2:
#宣布名单 x = ["ABC", "XYZ", "PQR"] y = ["PQR", "MNO", "YXZ"] z = ["123", "456", "789"] #清除清单之前先列印设定 print("Before clear() method...") print("x: ", x) print("y: ", y) print("z: ", z) #清除清单s x.clear() y.clear() z.clear() #清除清单后打印套 print("After clear() method...") print("x: ", x) print("y: ", y) print("z: ", z)
输出结果
Before clear() method... x: ['ABC', 'XYZ', 'PQR'] y: ['PQR', 'MNO', 'YXZ'] z: ['123', '456', '789'] After clear() method... x: [] y: [] z: []