Python基礎變量類型——List淺析
Python使用list
一、list
Python內置的一種數據類型是列表:list。list是一種有序的集合,可以隨時添加和刪除其中的元素。
比如,列出班里所有同學的名字,就可以用一個list表示:
classmates = ['Michael', 'Bob', 'Tracy']print(classmates)
變量classmates就是一個list。
len()函數1. 獲得list元素的個數:classmates = ['Michael', 'Bob', 'Tracy']print(len(classmates))
用索引來訪問list中每一個位置的元素,記得索引是從0開始的:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[0])
print(classmates[1])
print(classmates[2])
print(classmates[3])
當索引超出了范圍時,Python會報一個IndexError錯誤,所以,要確保索引不要越界,記得最后一個元素的索引是len(classmates) - 1。
如果要取最后一個元素,除了計算索引位置外,還可以用-1做索引,直接獲取最后一個元素:
print(classmates[-1])
以此類推,可以獲取倒數第2個、倒數第3個:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[-1])
print(classmates[-2])
print(classmates[-3])
print(classmates[-4])
當然,倒數第4個就越界了。

請輸入評論內容...
請輸入評論/評論長度6~500個字