Python 中元組和列表有什麼異同?


列表和元組在 Python 中均被稱作序列資料型別。兩種型別物件的元素均以逗號分隔,元素型別不一定相同。

相似之處

兩種型別的物件都可以進行連線、重複、索引和切片等操作

>>> #list operations
>>> L1=[1,2,3]
>>> L2=[4,5,6]
>>> #concatenation
>>> L3=L1+L2
>>> L3
[1, 2, 3, 4, 5, 6]
>>> #repetition
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> #indexing
>>> L3[4]
5
>>> #slicing
>>> L3[2:4]
[3, 4]


>>> #tuple operations
>>> T1=(1,2,3)
>>> T2=(4,5,6)
>>> #concatenation
>>> T3=T1+T2
>>> T3
(1, 2, 3, 4, 5, 6)
>>> #repetition
>>> T1*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> #indexing
>>> T3[4]
5
>>> #slicing
>>> T3[2:4]
(3, 4)

以下內建函式在兩種型別中都適用

len() − 返回序列中的元素個數

>>> L1=[45,32,16,72,24]
>>> len(L1)
5
>>> T1=(45,32,16,72,24)
>>> len(T3)

max() − 返回值最大的元素。

>>> max(L1)
72
>>> max(T1)
72

min() − 返回值最小的元素。

>>> max(T1)
72
>>> min(L1)
16
>>> min(T1)
16

不同之處

列表物件可變。因此,可以從列表中追加、更新或刪除元素。

>>> L1=[45,32,16,72,24]
>>> L1.append(56)
>>> L1
[45, 32, 16, 72, 24, 56]
>>> L1.insert(4,10) #insert 10 at 4th index
>>> L1
[45, 32, 16, 72, 10, 24, 56]
>>> L1.remove(16)
>>> L1
[45, 32, 72, 10, 24, 56]
>>> L1[2]=100 #update
>>> L1
[45, 32, 100, 10, 24, 56]

元組為不可變物件。任何嘗試對其進行修改的操作都會導致 AttributeError 錯誤。

T1.append(56)
AttributeError: 'tuple' object has no attribute 'append'
>>> T1.remove(16)
AttributeError: 'tuple' object has no attribute 'remove'
>>> T1[2]=100
TypeError: 'tuple' object does not support item assignment


更新日期:20-2-2020

816 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告