當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。