元組和列表十分類似,只不過元組和字符串一樣是 不可變的 即你不能修改元組。元組通過圓
括號中用逗號分割的項目定義。元組通常用在使語句或用戶定義的函數能夠安全地采用一組值
的時候,即被使用的元組的值不會改變。
#!/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個或1個項目的元組。一個空的元組由一對空的圓括號組成,如myempty = ()。然而,含
有單個元素的元組就不那么簡單了。你必須在第一個(唯一一個)項目后跟一個逗號,這樣
Python才能區分元組和表達式中一個帶圓括號的對象。即如果你想要的是一個包含項目2的元
組的時候,你應該指明singleton = (2 , )。
元組與打印語句
#!/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?