list和tuple
list和tuple都是sequence的一种,是有序列表,其内置的方法都相似,
>>> lst = [1, 2, 3, 4, 5]
>>> tpl = (1, 2, 3, 4, 5)
比如支持in运算,
>>> 1 in lst
True
>>> 1 in tpl
True
>>>
元素有坐标,
>>> lst.index(2)
1
>>> tpl.index(2)
1
>>>
支持index
>>> lst[3]
4
>>> tpl[3]
4
>>>
支持slicing
>>> lst[2:4]
[3, 4]
>>> tpl[2:4]
(3, 4)
>>>
list和tuple的区别:list是mutable的对象,内容可以更改,tuple则不是,所以是hashable的。关于mutable和hashable的概念,可以参考Python 里 immutable和hashable的概念
所以,一些list有的方法,在tuple里就不能实现:
>>> lst.append(6)
>>> lst
[1, 2, 3, 4, 5, 6]
>>> tpl.append(6)
Traceback (most recent call last):
File "", line 1, in
tpl.append(6)
AttributeError: 'tuple' object has no attribute 'append'
>>>
>>> lst.pop()
6
>>> tpl.pop()
Traceback (most recent call last):
File "", line 1, in
tpl.pop()
AttributeError: 'tuple' object has no attribute 'pop'
>>>
set和dict
set和dict的都是无序列表,没有index的概念。