python list和set区别_python 里list, tuple, set, dict的异同

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的概念。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值