list是處理一組有序項目的數據結構,即你可以在一個列表中存儲一個 序列 的項目。假想你有
一個購物列表,上面記載著你要買的東西,你就容易理解列表了。只不過在你的購物表上,可
能每樣東西都獨自占有一行,而在Python中,你在每個項目之間用逗號分割。
列表中的項目應該包括在方括號中,這樣Python就知道你是在指明一個列表。一旦你創建了一
個列表,你可以添加、刪除或是搜索列表中的項目。由于你可以增加或刪除項目,我們說列表
是 可變的 數據類型,即這種類型是可以被改變的。
#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist

print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist
輸出
$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
注意,我們在print語句的結尾使用了一個 逗號 來消除每個print語句自動打印的換行符。這樣
做有點難看,不過確實簡單有效。
一個購物列表,上面記載著你要買的東西,你就容易理解列表了。只不過在你的購物表上,可
能每樣東西都獨自占有一行,而在Python中,你在每個項目之間用逗號分割。
列表中的項目應該包括在方括號中,這樣Python就知道你是在指明一個列表。一旦你創建了一
個列表,你可以添加、刪除或是搜索列表中的項目。由于你可以增加或刪除項目,我們說列表
是 可變的 數據類型,即這種類型是可以被改變的。




















$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
注意,我們在print語句的結尾使用了一個 逗號 來消除每個print語句自動打印的換行符。這樣
做有點難看,不過確實簡單有效。