* python的串列等同於陣列,但可以彈性的調整大小、增加或刪除其中的元素,設計較為方便及好用
* 可以是一維、二維、甚至多維
* 串列的運作
```
list1=[] #建立一空串列
List2=[1,2,3,4,5]
list3=['apple','orange','banana']
list4=[1,2,34.56,'pineapple']
```
直接顯示
```
list2
[1,2,3,4,5]
list2[0]
1
list2[1:3]
[2,3]
```
串列的長度
```
len(list2)
5
```
append與insert方法
* append是將新值放在串列尾端,而Insert(index,value)將value加入於串列的索引為index處
```
list1.append(1)
list1
[1]
list1.append(2)
list1
[1,2]
list1.insert(1,4)
list1
[1,4,2]
```
* pop與remove方法
* pop()是移除串列的最後一個項目,pop(index)表示刪除第index個的項目。
* 利用remove(value)刪除串列中值為vale的項目,若有多個value項目,則只刪除第一個
```
list[2]
[1,2,3,4,5]
list2.pop()
5
list2
[1,2,3,4]
list2.pop(1)
2
list2
[1,3,4]
list2.remove(3)
list2
[1,4]
```
* count(value)可以計算value出現於串列的次數
* index(value)傳回value於串列的索引
```
list3[3]
['apple','orange','banana']
list3.append('apple')
list3
['apple','orage','banana','apple']
list3.count('apple')
2
list3.index['orange']
1
```
* sort將串列進行由小到大的排序
* reverse將串列反轉
```
list1
list1.append(5)
list1.sort
list1
list1.reverse()
```
* in、not in來判斷某項目是否存在於串列中
```
list1
[5,4,2,1]
5 in list1
True
8 not in list1
True
```
* sum, max, min
* +是將兩串列連在一起
* *是將串列複製幾次
```
list1
[5,4,2,1]
list2
[1,4]
list1+list2
[5,4,2,1,1,4]
list2*2
[1,4,1,4]
```
* 串列[start:end]
```
list1
[5,4,2,1]
list1[-1]
list1[-3]
list1[-3:-1] #印出索引-3到-2的串列項目
[4,2]
list1[-4:4] #索引-4到3的項目
[5,4,2,1]
```
* 搭配for印出所有項目
```
list3=['apple','oranage','banana','kiwi']
for i in range(len(list3))
print('list3[%d] = %s' %(i,list[i]))
```
for搭配in
```
for i in list3:
print(i,end="***")
```
* 抽籤、或樂透數字的設定
* random.randint(1,49)