初學python的同學可能無法理解,爲什麼單個元素的元組要在後面加上逗號呢,如a=(123,)。看完下面的例子,我想各位應該就清楚了。
>>> a=(1,2)
>>> b=(3)
>>> c=a+b
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: can only concatenate tuple (not "int") to tuple
>>> d=(3,)
>>> c=a+d
>>> print c
(1, 2, 3)仔細看看錯誤信息:“TypeError: can only concatenate tuple (not "int") to tuple”。原來python解釋器把(3)當作一個算數表達式來處理的,它的結果就是一個int型對象。爲了和只有單個元素的元組區分,python規定要在元素後面帶上一個逗號,例如d=(3,)。