python list and tuple

python list: x = [1,2,3]

list 是可改變的

例如: x.append(4)


python tuple: x = (1,2,3)
執行: x.append(4)
會有error:


Traceback (most recent call last):
  File "<pyshell#232>", line 1, in <module>
    a.append(4)
AttributeError: 'tuple' object has no attribute 'append'

這是唯獨的陣列, 不能執行append 或 remove 之類的function

而這樣定義函式:

def test(*args):
    print type(args)

取得的args 資料型態是 tuple


def g(*args):
print type(args)


>>> g(5)
<type 'tuple'>


而 dict  型別可以用tuple 來當作 key
但類似的 list 就不能(會導致下列錯誤)


Traceback (most recent call last):
  File "<pyshell#248>", line 1, in <module>
    c[x]
TypeError: list objects are unhashable



留言

熱門文章