list和tuple
list和tuple都是 sequence type 的一種,是有序清單,其内置的方法都相似。舉例來說,有 l 和 t 分别儲存 list 和 tuple
l = [1, 2, 3, 4, 5]
t = (1, 2, 3, 4, 5)
比如支援in運算,
>>> 1 in l
True
>>> 1 in t
True
>>>
元素有坐标,
>>> l.index(2)
1
>>> t.index(2)
1
>>>
支援index
>>> l[3]
4
>>> t[3]
4
>>>
支援slicing
>>> l[2:4]
[3, 4]
>>> t[2:4]
(3, 4)
>>>
list和tuple的差別:list是mutable的對象,内容可以更改,tuple則不是,是以是hashable的。關于mutable和hashable的概念,可以參考Python 裡 immutable和hashable的概念
是以,一些list有的方法,在tuple裡就不能實作:
>>> l.append(6)
>>> l
[1, 2, 3, 4, 5, 6]
>>> t.append(6)
Traceback (most recent call last):
File "", line 1, in
t.append(6)
AttributeError: 'tuple' object has no attribute 'append'
>>>
>>> l.pop()
6
>>> t.pop()
Traceback (most recent call last):
File "", line 1, in
t.pop()
AttributeError: 'tuple' object has no attribute 'pop'
>>>
set和dict
set和dict的都是無序清單,沒有index的概念。