元組和列表十分類似,只不過(guò)元組和字符串一樣是 不可變的 即你不能修改元組。元組通過(guò)圓
括號(hào)中用逗號(hào)分割的項(xiàng)目定義。元組通常用在使語(yǔ)句或用戶定義的函數(shù)能夠安全地采用一組值
的時(shí)候,即被使用的元組的值不會(huì)改變。

#!/usr/bin/python
#
 Filename: using_tuple.py
zoo = ('wolf''elephant''penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo 
= ('monkey''dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]
輸出
$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
 
含有0個(gè)或1個(gè)項(xiàng)目的元組。一個(gè)空的元組由一對(duì)空的圓括號(hào)組成,如myempty = ()。然而,含
有單個(gè)元素的元組就不那么簡(jiǎn)單了。你必須在第一個(gè)(唯一一個(gè))項(xiàng)目后跟一個(gè)逗號(hào),這樣
Python才能區(qū)分元組和表達(dá)式中一個(gè)帶圓括號(hào)的對(duì)象。即如果你想要的是一個(gè)包含項(xiàng)目2的元
組的時(shí)候,你應(yīng)該指明singleton = (2 , )。

元組與打印語(yǔ)句
#!/usr/bin/python
#
 Filename: print_tuple.py
age = 22
name 
= 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name 

輸出
$ python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?