列表:一種有序的數據集合。
特點:
1,支持增刪改查
2,列表中的數據是可以改變的(數據項可以改變,但是內存地址不會改變)
3,用[ ]表示列表類型,數據項之間用逗號隔開。
注意:數據項可以是任意類型的數據。
4,支持索引和切片
【補充知識】
代碼
L=[1,2,3,'hello']
print(type(L))#返回L的數據類型
print(len(L))#返回列表的數據個數
strA='python'
print(len(strA))#返回字符串的字符的個數
運行結果
<class 'list'>
4
6
【查找】
代碼
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print(ListA)#輸出完整的列表
print(ListA[0])#輸出第一個元素
print(ListA[1:3])#輸出第二個到第三個的元素
print(ListA[2: ])#輸出第三個元素開始到最後的元素
print(ListA[::-1])#從右向左輸出元素
print(ListA*3)#將列表中的數據複製三次
運行結果
['python', 11, 22, 33, True]
python
[11, 22]
[22, 33, True]
[True, 33, 22, 11, 'python']
['python', 11, 22, 33, True, 'python', 11, 22, 33, True, 'python', 11, 22, 33, True]
代碼
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print(ListA.index(33))#返回的是33的索引值
運行結果
3
代碼
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print(ListA.index(33,1,4))#表示從第二個元素到第四個元素查找33,並返回33的索引
運行結果
3
【增加】
1,append()
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print('追加之前',ListA)
ListA.append(['aaa','ssa'])
ListA.append(666)
print('追加之後',ListA)
追加之前 ['python', 11, 22, 33, True]
追加之後 ['python', 11, 22, 33, True, ['aaa', 'ssa'], 666]
2,insert(索引,添加的數據項內容)
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print('追加之前',ListA)
ListA.insert(1,'hello world')
print('追加之後',ListA)
追加之前 ['python', 11, 22, 33, True]
追加之後 ['python', 'hello world', 11, 22, 33, True]
3,extend
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print('追加前',ListA)
Data=list(range(10))
ListA.extend(Data)#批量添加
print('追加後1',ListA)
ListA.extend([3666,8552])
print('追加後2',ListA)
追加前 ['python', 11, 22, 33, True]
追加後1 ['python', 11, 22, 33, True, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
追加後2 ['python', 11, 22, 33, True, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3666, 8552]
【修改】
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print('修改前',ListA)
ListA[0]='hello'
print('修改後',ListA)
修改前 ['python', 11, 22, 33, True]
修改後 ['hello', 11, 22, 33, True]
【刪除】
1,del()
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print('刪除前',ListA)
del ListA[0]#刪除列表中第一個元素
print('刪除後1:',ListA)
del ListA[1:3]#刪除列表中第二個到第三個元素
print("刪除後2:",ListA)
刪除前 ['python', 11, 22, 33, True]
刪除後1: [11, 22, 33, True]
刪除後2: [11, True]
2,remove()
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print('刪除前',ListA)
ListA.remove(22)#移除具體的元素,參數是具體的數據項的值
print("刪除後:",ListA)
刪除前 ['python', 11, 22, 33, True]
刪除後: ['python', 11, 33, True]
3,pop()
ListA=['python',11,22,33,True]#包含字符串,數字,布爾類型的數據項
print('刪除前',ListA)
ListA.pop(1)#移除該索引下的數據項,參數是索引值
print("刪除後:",ListA)
刪除前 ['python', 11, 22, 33, True]
刪除後: ['python', 22, 33, True]
自我覺得用一些簡單的代碼更容易記住一些基礎的知識~