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
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
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语句自动打印的换行符。这样
做有点难看,不过确实简单有效。