当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python List clear()用法及代码示例


列出 clear() 方法

clear() 方法用于清除列表,即用于从列表中删除所有元素。

用法:

    list_name.clear()

参数:

  • 它不接受任何参数。

返回值:

这个方法的返回类型是<class 'NoneType'>,它什么都不返回。

范例1:

# declaring a list
cities = ["New Delhi", "Mumbai", "Banglore"]

# printing elements before clearing the list
print("Before clear() method...")
print("cities = ", cities)

# clearing the list
cities.clear()

# printing elements after clearing the list
print("After clear() method...")
print("cities = ", cities)

输出

Before clear() method...
cities =  ['New Delhi', 'Mumbai', 'Banglore']
After clear() method...
cities =  []

范例2:

# declaring the lists
x = ["ABC", "XYZ", "PQR"]
y = ["PQR", "MNO", "YXZ"]
z = ["123", "456", "789"]

# printing sets before clearing the list
print("Before clear() method...")
print("x:", x)
print("y:", y)
print("z:", z)

# clearing the lists
x.clear()
y.clear()
z.clear()

# printing sets after clearing the list
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: []


相关用法


注:本文由纯净天空筛选整理自 Python List clear() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。