Python元组与列表的区别

红太狼 2022-05-18 07:37 293阅读 0赞

Python元组与列表的区别

1. Literal(字面意义的)
  1. someTuple = (1,2)
  2. someList = [1,2]
2. Size(大小)
  1. a = tuple(range(1000))
  2. b = list(range(1000))
  3. a.__sizeof__() # 8024
  4. b.__sizeof__() # 9088

Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements.

3. Permitted operations(允许操作)
  1. b = [1,2]
  2. b[0] = 3 # [3, 2]
  3. a = (1,2)
  4. a[0] = 3 # Error

That also means that you can’t delete an element or sort a tuple. However, you could add new element to both list and tuple with the only difference that you will change id of the tuple by adding element

  1. a = (1,2)
  2. b = [1,2]
  3. id(a) # 140230916716520
  4. id(b) # 748527696
  5. a += (3,) # (1, 2, 3)
  6. b += [3] # [1, 2, 3]
  7. id(a) # 140230916878160
  8. id(b) # 748527696
4. Usage(用法)

As a list is mutable, it can’t be used as a key in a dictionary, whereas a tuple can be used.

  1. a = (1,2)
  2. b = [1,2]
  3. c = {a: 1} # OK
  4. c = {b: 1} # Error

发表评论

表情:
评论列表 (有 0 条评论,293人围观)

还没有评论,来说两句吧...

相关阅读